题目地址:http://poj.org/problem?id=2186
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000+10;
bool vis[maxn];
int ID[maxn]; //点的颜色编号
int index,ncolor;
vector<int> dfn(maxn),low(maxn),st;
vector<vector<int> > color(maxn); //同一种颜色的点
vector<vector<int> > G(maxn);
void Tarjan(int u)
{dfn[u]=low[u]=++index;vis[u]=true;st.push_back(u);for(int i=0;i<G[u].size();i++){int v=G[u][i];if(!vis[v]){Tarjan(v);low[u]=min(low[u],low[v]);}else if(find(st.begin(),st.end(),v)!=st.end()) //in stacklow[u]=min(low[u],dfn[v]);}if(dfn[u]==low[u]){int v; ncolor++;do{v=st.back(); st.pop_back();color[ncolor].push_back(v);ID[v]=ncolor;}while(v!=u);}
}
int getGraph(int n)
{index=ncolor=0;for(int i=1;i<=n;i++)if(!vis[i]) Tarjan(i);
}
int solve() //找出度为0的
{int m=0,ans; //m标记出度为0的点有几个 for(int i=1;i<=ncolor;i++){bool ok=true;for(int j=0;j<color[i].size()&&ok;j++){int u=color[i][j];for(int k=0;k<G[u].size()&&ok;k++){int v=G[u][k];if(ID[u]!=ID[v]) //有出度 ok=false; }}if(ok) m++,ans=i;if(m>1) break;}if(m!=1) return 0;else return color[ans].size();
}
int main()
{int n,m;cin>>n>>m;while(m--){int u,v;cin>>u>>v;G[u].push_back(v);}getGraph(n); cout<<solve();return 0;
}