首页 > 代码库 > POJ 1236 强联通分量

POJ 1236 强联通分量

链接:

http://poj.org/problem?id=1236

代码:

31 int index = 0;
32 int low[MAXN], dfn[MAXN];
33 int vis[MAXN], bel[MAXN];
34 VI G[MAXN];
35 stack<int> S;
36 int scc_cnt;
37 
38 void tarjan(int u) {
39     dfn[u] = low[u] = ++index;
40     S.push(u); vis[u] = 1;
41     rep(i, 0, G[u].size()) {
42         int v = G[u][i];
43         if (!dfn[v]) {
44             tarjan(v);
45             low[u] = min(low[u], low[v]);
46         }
47         else if (vis[v]) low[u] = min(low[u], dfn[v]);
48     }
49     if (low[u] == dfn[u]) {
50         scc_cnt++;
51         while (1) {
52             int now = S.top(); S.pop();
53             vis[now] = 0;
54             bel[now] = scc_cnt;
55             if (now == u) break;
56         }
57     }
58 }
59 
60 int n;
61 int in[MAXN], out[MAXN];
62 
63 void scc() {
64     index = scc_cnt = 0;
65     memset(dfn, 0, sizeof(dfn));
66     rep(i, 0, n) if (!dfn[i]) tarjan(i);
67 }
68 
69 int main() {
70     cin >> n;
71     int a;
72     rep(i, 0, n) while (cin >> a, a) G[i].pb(a - 1);
73     scc();
74     if (scc_cnt == 1) {
75         cout << 1 << endl << 0 << endl;
76         return 0;
77     }
78     rep(u, 0, n) rep(i, 0, G[u].size()) {
79         int v = G[u][i];
80         if (bel[u] != bel[v]) {
81             out[bel[u]]++;
82             in[bel[v]]++;
83         }
84     }
85     int in_tot = 0, out_tot = 0;
86     rep(i, 1, scc_cnt + 1) {
87         if (!in[i]) in_tot++;
88         if (!out[i]) out_tot++;
89     }
90     cout << in_tot << endl << max(in_tot, out_tot) << endl;
91     return 0;
92 }

 

POJ 1236 强联通分量