Description
Input
Output
Sample Input
3 3 1 2 2 1 2 3
Sample Output
1
Hint
Source
#include<cstdio> #include<string> #include<iostream> #include<algorithm> using namespace std; const int maxn=10006; int DFN[maxn]; int low[maxn]; int sccnum[maxn]; int in[maxn]; int out[maxn]; int num[maxn]; int stack[maxn]; bool instack[maxn]; struct node { int next; int to; }edge[maxn*5]; int head[maxn]; int tot,top,index,sccNum,n; void addedge(int from,int to) { edge[tot].to=to; edge[tot].next=head[from]; head[from]=tot++; } void tarjan(int u) { DFN[u]=low[u]=++index; stack[top++]=u; instack[u]=1; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; if(DFN[v]==0) { tarjan(v); if(low[u]>low[v]) low[u]=low[v]; } else if(instack[v]) if(low[u]>DFN[v]) low[u]=DFN[v]; } if(DFN[u]==low[u]) { sccNum++; do { top--; sccnum[stack[top]]=sccNum; num[sccNum]++; instack[stack[top]]=0; }while(stack[top]!=u); } } void solve() { memset(instack,0,sizeof(instack)); memset(num,0,sizeof(num)); memset(DFN,0,sizeof(DFN)); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); index=0; top=0; sccNum=0; for(int i=1;i<=n;i++) if(DFN[i]==0) tarjan(i); } int main() { int m; while(~scanf("%d%d",&n,&m)) { int x,y; tot=0; memset(head,-1,sizeof(head)); for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); addedge(x,y); } solve(); for(int i=1;i<=n;i++) { for(int j=head[i];j!=-1;j=edge[j].next) { if(sccnum[i]!=sccnum[edge[j].to]) { out[sccnum[i]]++; in[sccnum[edge[j].to]]++; } } } int ans=0,j,i,cnt=0; for(i=1;i<=sccNum;i++) { if(out[i]==0) { cnt++; } } if(cnt>1 || cnt==0) printf("0\n"); else printf("%d\n",num[cnt]); } return 0; }