Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 14393 | Accepted: 5718 |
Description
Input
Output
Sample Input
3 3 1 2 2 1 2 3
Sample Output
1
Hint
Source
#include<cstdio> #define min(a,b) a<b?a:b using namespace std; const int mm=50005; const int mn=10001; int s[mm],t[mm],p[mm]; int h[mn],id[mn],q[mn],dfn[mn],low[mn],num[mn]; int i,j,k,n,m,tsp,qe,cnt; void dfs(int u) { int i,v; dfn[u]=low[q[qe++]=u]=++tsp; for(i=h[u];i>=0;i=p[i]) if(!dfn[v=t[i]]) dfs(v),low[u]=min(low[u],low[v]); else if(id[v]<0)low[u]=min(low[u],dfn[v]); if(low[u]==dfn[u]) { num[id[u]=++cnt]=1; while((v=q[--qe])!=u)++num[id[v]=cnt]; } } void tarjan() { int i; for(tsp=qe=cnt=i=0;i<=n;++i)id[i]=-1,dfn[i]=0; for(i=1;i<=n;++i) if(!dfn[i])dfs(i); } int main() { while(scanf("%d%d",&n,&m)!=-1) { for(i=0;i<=n;++i)h[i]=-1; for(k=0;k<m;++k) { scanf("%d%d",&i,&j); s[k]=i,t[k]=j,p[k]=h[i],h[i]=k; } tarjan(); for(i=0;i<=cnt;++i)q[i]=0; for(i=0;i<m;++i) if((j=id[s[i]])!=id[t[i]])++q[j]; for(tsp=0,i=1;i<=cnt;++i) if(!q[i])++tsp,j=i; if(tsp>1)printf("0\n"); else printf("%d\n",num[j]); } return 0; }