//思路:强连通分支然后重新构图,然后再判断出度为0的强连通分支里面的元素,如果出度为0的强连通有多个,则一定没有解!! #include <iostream> #include <string> #include <vector> #define maxn 10001 using namespace std; int n,m,vis[maxn],ord[maxn],cnt,degree[maxn],out[maxn],ans; vector<int>G[maxn]; vector<int>G1[maxn]; void dfs(int u) { int i; vis[u] = 1; for(i = 0; i<G[u].size(); i++) if(!vis[G[u][i]])dfs(G[u][i]); ord[cnt++] = u; } void dfs1(int u) { int i; degree[u] = ans; vis[u] = 1; for(i = 0; i<G1[u].size(); i++) if(!vis[G1[u][i]])dfs1(G1[u][i]); } int main() { int i,u,v,j,p,sum,f; while(scanf("%d %d",&n,&m)!=EOF) { for(i = 1; i<=n; i++) { G[i].clear(); G1[i].clear(); } for(i = 0; i<m; i++) { scanf("%d %d",&u,&v); G[u].push_back(v); G1[v].push_back(u); } memset(out,0,sizeof(out)); memset(vis,0,sizeof(vis)); sum = p = ans = cnt = 0; for(i = 1; i<=n; i++) if(!vis[i])dfs(i); memset(vis,0,sizeof(vis)); for(i = cnt - 1; i>=0; i--) if(!vis[ord[i]]) { ans++; dfs1(ord[i]); } for(i = 1; i<=n; i++) for(j = 0; j<G[i].size(); j++)//找出度为0的点; { if(degree[i]!=degree[G[i][j]]) { out[degree[i]]++; } } for(i = 1; i<=ans; i++)//标志出度为0的点,如果有多个点,此图肯定不连通 if(out[i] == 0) { p++; f = i; } if(p>1)//不连通 { printf("%d/n",0); continue; } for(i = 1; i<=n; i++)//度数为f强连通里面的数 if(degree[i] == f)sum++; printf("%d/n",sum); } return 0; }