题目:http://acm.split.hdu.edu.cn/showproblem.php?pid=3342
拓扑排序找环即可。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=10005;
int in[maxn],sum,n,m,X[maxn],Y[maxn],fa[maxn];
vector<int > G[maxn];
char c[maxn];
void toposort(){
queue<int>s;
int flag=0;
for(int i=0;i<n;i++){ //注意是从0开始还是从1开始
if(in[i]==0) //收入入度为0的点
s.push(i);
}
while(!s.empty()){ //由于互为环的点的入度是不会为0的,所以不会被push进来
if(s.size()>1) //只要入度不唯一,排名就不确定。
flag=1;
int pos=s.front();
s.pop(),sum--;
for(int i=0;i<G[pos].size();i++){
in[G[pos][i]]--; //与pos相连的点入度减一
if(in[G[pos][i]]==0)
s.push(G[pos][i]); //收入新一波入度为0的点
}
}
if(sum>0) printf("NO\n"); //有环,sum无法--
else printf("YES\n");
}
int main(){
while(scanf("%d%d",&n,&m)==2&&n){
memset(G,0,sizeof(G));
memset(in,0,sizeof(in));
int x,y;
sum=n;
for(int i=0;i<m;i++){
scanf("%d%d",&x,&y);
G[x].push_back(y);
in[y]++;
}
toposort();
}
return 0;
}