1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <iostream> #include <cstdio> #include <map> #include <stack> #include <string> using namespace std; const int N = 8e3 + 10, M = 3e4 + 10; int n, m; bool vis[N]; stack <int> stk; map <string, int> name; int idx = -1, hd[N], nxt[M], edg[M]; int cnt, stmp, id[N], dfn[N], low[N]; void tarjan (int x) { dfn[x] = low[x] = ++stmp; stk.push(x); vis[x] = true; for (int i = hd[x]; ~i; i = nxt[i]) if (!dfn[edg[i]]) { tarjan(edg[i]); low[x] = min(low[x], low[edg[i]]); } else if (vis[edg[i]]) low[x] = min(low[x], dfn[edg[i]]); if (dfn[x] == low[x]) { cnt++; int y; do { y = stk.top(); stk.pop(); vis[y] = false; id[y] = cnt; } while (y != x); } } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main () { string a, b; cin >> n; for (int i = 0; i < n << 1; i++) hd[i] = -1; for (int i = 0; i < n; i++) { cin >> a >> b; name[a] = i << 1; name[b] = i << 1 | 1; add(i << 1, i << 1 | 1); } cin >> m; for (int i = 0; i < m; i++) { cin >> a >> b; add(name[b], name[a]); } for (int i = 0; i < n << 1; i++) if (!dfn[i]) tarjan(i); for (int i = 0; i < n; i++) if (id[i << 1] == id[i << 1 | 1]) cout << "Unsafe" << endl; else cout << "Safe" << endl; return 0; }
|