1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| #include <bits/stdc++.h> using namespace std;
const int MAXN=10005;
stack <int> S; bool inst[MAXN]; vector <int> V[MAXN]; int n,m,col,cnt,dfn[MAXN],low[MAXN],color[MAXN],colt[MAXN],du[MAXN];
void inti(void) { cnt=col=0; memset(du,0,sizeof(du)); memset(dfn,0,sizeof(dfn)); memset(low,0,sizeof(low)); memset(colt,0,sizeof(colt)); memset(color,0,sizeof(color)); memset(inst,false,sizeof(inst)); for (int i=0;i<MAXN;i++) V[i].clear(); }
void Tarjan(int now) { dfn[now]=low[now]=++cnt; inst[now]=true; S.push(now); for (int i=0;i<V[now].size();i++) { int next=V[now][i]; if (!dfn[next]) { Tarjan(next); low[now]=min(low[now],low[next]); } else if (inst[next]) low[now]=min(low[now],dfn[next]); } if (dfn[now]==low[now]) { col++; int s; do { s=S.top(); S.pop(); inst[s]=false; color[s]=col; colt[col]++; } while (s!=now); } }
void ReGraph(void) { for (int i=1;i<=n;i++) for (int j=0;j<V[i].size();j++) if (color[i]!=color[V[i][j]]) du[color[i]]++; }
int main() { int x,y,ans=0; inti(); scanf("%d%d",&n,&m); while (m--) { int x,y; scanf("%d%d",&x,&y); V[x].push_back(y); } for (int i=1;i<=n;i++) if (!dfn[i]) Tarjan(i); ReGraph(); for (int i=1;i<=col;i++) if (du[i]==0) { if (ans) return printf("0")&0; ans=colt[i]; } return printf("%d",ans)&0; }
|