解题思路:没有环的拓扑图、
连接:http://acm.hdu.edu.cn/showproblem.php?pid=3342
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> using namespace std; const int MAX=100+10; int c[MAX]; int topo[MAX][MAX]; int map[MAX][MAX]; int m; int n; int t; bool dfs(int k) { c[k]=-1; for(int i=0;i<n;i++) { if(map[k][i]) { if(c[i]<0) { return false; } else if(!c[i]&&!dfs(i)) { return false; } } } c[k]=1; //topo[--t]=k; 记录路劲 return true; } bool toposort() { //t=n; memset(c,0,sizeof(c)); for(int i=0;i<n;i++) { if(!c[i]) { if(!dfs(i)) { return false; } } } return true; } int main() { while(scanf("%d%d",&n,&m),n+m) { memset(map,0,sizeof(map)); while(m--) { int a; int b; scanf("%d%d",&a,&b); map[a][b]=1; } if(toposort()) { printf("YES\n"); } else printf("NO\n"); } return 0; }