标签:
Description
Input
Output
Sample Input
3 3 1 2 2 1 2 3
Sample Output
1
Hint
Source
1 //It is made by jump~ 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cstdio> 6 #include <cmath> 7 #include <algorithm> 8 #include <ctime> 9 #include <vector> 10 #include <queue> 11 #include <map> 12 #ifdef WIN32 13 #define OT "%I64d" 14 #else 15 #define OT "%lld" 16 #endif 17 using namespace std; 18 typedef long long LL; 19 const int MAXN = 10011; 20 const int MAXM = 50011; 21 int n,m; 22 int ecnt,cnt,total; 23 int first[MAXN],next[MAXM],to[MAXM]; 24 int belong[MAXN]; 25 int dfn[MAXN],low[MAXN]; 26 bool pd[MAXN]; 27 int Stack[MAXN],top; 28 int out[MAXN]; 29 int ans,jilu; 30 31 inline int getint() 32 { 33 int w=0,q=0; 34 char c=getchar(); 35 while((c<‘0‘ || c>‘9‘) && c!=‘-‘) c=getchar(); 36 if (c==‘-‘) q=1, c=getchar(); 37 while (c>=‘0‘ && c<=‘9‘) w=w*10+c-‘0‘, c=getchar(); 38 return q ? -w : w; 39 } 40 41 inline void Init(){ 42 ecnt=0; cnt=0; total=0; top=0; 43 memset(first,0,sizeof(first)); 44 memset(pd,0,sizeof(pd)); 45 memset(dfn,0,sizeof(dfn)); 46 memset(Stack,0,sizeof(Stack)); 47 } 48 49 inline void link(int x,int y){ 50 next[++ecnt]=first[x]; first[x]=ecnt; to[ecnt]=y; 51 } 52 53 inline void dfs(int x){ 54 dfn[x]=++total; low[x]=dfn[x]; 55 pd[x]=1; 56 Stack[++top]=x; 57 for(int i=first[x];i;i=next[i]) { 58 int v=to[i]; 59 if(!dfn[v]) { 60 dfs(v); 61 low[x]=min(low[x],low[v]); 62 } 63 else if(pd[v] && low[v]<low[x]) low[x]=low[v]; 64 } 65 if(dfn[x]==low[x]) { 66 cnt++; 67 int now=Stack[top]; 68 do{ 69 belong[now]=cnt; 70 pd[now]=0; top--; 71 if(now==x) break; 72 now=Stack[top]; 73 }while(1); 74 } 75 } 76 77 inline void tarjan(){ 78 for(int i=1;i<=n;i++) if(!dfn[i]) dfs(i); 79 } 80 81 inline void solve(){ 82 while(scanf("%d%d",&n,&m)!=EOF) { 83 Init(); 84 int x,y; 85 for(int i=1;i<=m;i++) { 86 x=getint(); y=getint(); 87 link(x,y); 88 } 89 tarjan(); 90 for(int i=1;i<=n;i++){ 91 for(int j=first[i];j;j=next[j]) { 92 int v=to[j]; 93 if(belong[v]!=belong[i]) { 94 out[belong[i]]++; 95 } 96 } 97 } 98 ans=0,jilu=0; 99 for(int i=1;i<=cnt;i++){ 100 if(out[i]==0) { 101 ans++; jilu=i; 102 } 103 } 104 if(ans==1) { 105 ans=0; 106 for(int i=1;i<=n;i++) { 107 if(belong[i]==jilu) ans++; 108 } 109 printf("%d\n",ans); 110 } 111 else printf("0\n"); 112 } 113 } 114 115 int main() 116 { 117 solve(); 118 return 0; 119 }
标签:
原文地址:http://www.cnblogs.com/ljh2000-jump/p/5628445.html