![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
/* Name: 利用拓扑排序过程判断有向图是否有回路及自环 Copyright: Author: Try86 Date: 15/04/12 21:15 Description: */ #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> using namespace std; const int N = 105; int color[N], flag; struct node { int v; node *next; node(int vv, node *p) { v = vv; next = p; } }; struct graph { node *link; }G[N]; void init(int n) { for (int i=0; i<n; ++i) G[i].link = NULL; return ; } void buildG(int u, int v) { node *p = new node(v, G[u].link); G[u].link = p; return ; } void dfsVisit(int u) { color[u] = 1; for (node *p=G[u].link; p; p=p->next) { if (color[p->v] == 1) {//发现回路 flag = false; return ; } if (!color[p->v]) dfsVisit(p->v); } color[u] = 2; return ; } void topoSort(int n) { flag = true; memset(color, 0, sizeof(color)); for (int i=0; i<n; ++i) { if (!color[i]) { dfsVisit(i); if (!flag) return ; } } return ; } void del(node *p) { if (!p) return ; del(p->next); delete p; } int main() { int n, m; while (scanf("%d%d", &n, &m), n+m) { init(n); int u, v; for (int i=0; i<m; ++i) { scanf ("%d%d", &u, &v); buildG(u, v); } topoSort(n); if (flag) printf ("YES\n"); else printf ("NO\n"); for (int i=0; i<n; ++i) del(G[i].link); } return 0; }