标签:
2 4 0 3 2 1 2 1 3
4 2
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 20010; 4 vector<int>g[maxn]; 5 int dfn[maxn],low[maxn],id[maxn],od[maxn]; 6 int belong[maxn],scc,idx; 7 bool instack[maxn]; 8 stack<int>stk; 9 void init() { 10 for(int i = 0; i < maxn; ++i) { 11 dfn[i] = belong[i] = 0; 12 id[i] = od[i] = 0; 13 instack[i] = false; 14 g[i].clear(); 15 } 16 scc = idx = 0; 17 while(!stk.empty()) stk.pop(); 18 } 19 void tarjan(int u) { 20 dfn[u] = low[u] = ++idx; 21 instack[u] = true; 22 stk.push(u); 23 for(int i = g[u].size()-1; i >= 0; --i) { 24 if(!dfn[g[u][i]]) { 25 tarjan(g[u][i]); 26 low[u] = min(low[u],low[g[u][i]]); 27 } else if(instack[g[u][i]]) low[u] = min(low[u],dfn[g[u][i]]); 28 } 29 if(dfn[u] == low[u]) { 30 scc++; 31 int v; 32 do { 33 instack[v = stk.top()] = false; 34 stk.pop(); 35 belong[v] = scc; 36 } while(v != u); 37 } 38 } 39 int main() { 40 int kase,n,m,u,v; 41 scanf("%d",&kase); 42 while(kase--) { 43 scanf("%d%d",&n,&m); 44 init(); 45 for(int i = 0; i < m; ++i) { 46 scanf("%d%d",&u,&v); 47 g[u].push_back(v); 48 } 49 for(int i = 1; i <= n; ++i) 50 if(!dfn[i]) tarjan(i); 51 if(scc <= 1) { 52 puts("0"); 53 continue; 54 } 55 for(int i = 1; i <= n; ++i) 56 for(int j = g[i].size()-1; j >= 0; --j) 57 if(belong[i]!=belong[g[i][j]]) { 58 id[belong[g[i][j]]]++; 59 od[belong[i]]++; 60 } 61 int a = 0,b = 0; 62 for(int i = 1; i <= scc; ++i) { 63 if(!id[i]) a++; 64 if(!od[i]) b++; 65 } 66 printf("%d\n",max(a,b)); 67 } 68 return 0; 69 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4693022.html