3 3 1 2 2 1 2 3
1
1 #include <cstdio> 2 #include <iostream> 3 #include <stack> 4 #include <cstring> 5 using namespace std; 6 const int maxn = 10010; 7 int dfn[maxn],low[maxn],head[maxn],belong[maxn],scc,tot,idx; 8 int outde[maxn]; 9 bool instack[maxn]; 10 stack<int>stk; 11 struct arc{ 12 int to,next; 13 arc(int x = 0,int y = -1){ 14 to = x; 15 next = y; 16 } 17 }e[200000]; 18 void add(int u,int v){ 19 e[tot] = arc(v,head[u]); 20 head[u] = tot++; 21 } 22 void tarjan(int u){ 23 dfn[u] = low[u] = idx++; 24 stk.push(u); 25 instack[u] = true; 26 for(int i = head[u]; ~i; i = e[i].next){ 27 if(dfn[e[i].to] == -1){ 28 tarjan(e[i].to); 29 low[u] = min(low[u],low[e[i].to]); 30 }else if(instack[e[i].to]) low[u] = min(low[u],dfn[e[i].to]); 31 } 32 if(dfn[u] == low[u]){ 33 scc++; 34 int v; 35 do{ 36 v = stk.top(); 37 stk.pop(); 38 instack[v] = false; 39 belong[v] = scc; 40 }while(v != u); 41 } 42 } 43 int main(){ 44 int n,m,u,v; 45 while(~scanf("%d %d",&n,&m)){ 46 memset(head,-1,sizeof(head)); 47 memset(belong,0,sizeof(belong)); 48 memset(dfn,-1,sizeof(dfn)); 49 memset(low,-1,sizeof(low)); 50 memset(outde,0,sizeof(outde)); 51 while(!stk.empty()) stk.pop(); 52 tot = scc = idx = 0; 53 for(int i = 0; i < m; ++i){ 54 scanf("%d %d",&u,&v); 55 add(u,v); 56 } 57 for(int i = 1; i <= n; ++i) 58 if(dfn[i] == -1) tarjan(i); 59 for(int i = 1; i <= n; ++i) 60 for(int j = head[i]; ~j; j = e[j].next) 61 if(belong[i] != belong[e[j].to]) outde[belong[i]]++; 62 int ans = 0,p = 0; 63 for(int i = 1; i <= scc; ++i) 64 if(!outde[i]) p = i,ans++; 65 if(ans == 1){ 66 ans = 0; 67 for(int i = 1; i <= n; ++i) if(belong[i] == p) ans++; 68 printf("%d\n",ans); 69 }else puts("0"); 70 } 71 return 0; 72 }