vector<int> G[N];//G[i]表示i节点所指向的所有其他点 int in[N]; //节点入度 booljudgeTopSort(int n, int m){ //判断该图是否可拓扑排序 stack<int> S; int cnt = 0; //记录可拆解的点数目 for (int i = 1; i <= n; i++) if (in[i] == 0) //入度为0,入栈 S.push(i); while (!S.empty()) { int x = S.top(); //取栈顶元素 S.pop(); cnt++; //可拆点数+1 for (int i = 0; i < G[x].size(); i++) { int y = G[x][i]; in[y]--; //入度减一 if (in[y] == 0) //入度为0,入栈 S.push(y); } } if (cnt == n) //AOV网点数等于图的点数,不存在环 returntrue; else//AOV网点数不等于图的点数,存在环 returnfalse; } intmain(){ while (scanf("%d%d", &n, &m) == 2 && n) { memset(in, 0, sizeof(in)); for (int i = 1; i <= n; i++) G[i].clear(); while (m--) { int x, y; scanf("%d%d", &x, &y); G[x].push_back(y); in[y]++; } printf("%s\n", judgeTopSort(n, m) ? "YES" : "NO"); } return0; }
vector<int> G[N];//G[i]表示i节点所指向的所有其他点 int in[N]; //节点入度 int path[N]; //存储路径 booltopSort(int n, int m){ //判断该图是否可拓扑排序 stack<int> S; int cnt = 0; //记录可拆解的点数目 for (int i = 1; i <= n; i++) if (in[i] == 0) //入度为0,入栈 S.push(i); while (!S.empty()) { int x = S.top(); //取栈顶元素 S.pop(); path[++cnt] = x; //存储可拆点 for (int i = 0; i < G[x].size(); i++) { int y = G[x][i]; in[y]--; //入度减一 if (in[y] == 0) //入度为0,入栈 S.push(y); } } if (cnt == n) //AOV网点数等于图的点数,不存在环 returntrue; else//AOV网点数不等于图的点数,存在环 returnfalse; } intmain(){ while (scanf("%d%d", &n, &m) == 2 && n) { memset(in, 0, sizeof(in)); memset(path, 0, sizeof(path)); for (int i = 1; i <= n; i++) G[i].clear(); while (m--) { int x, y; scanf("%d%d", &x, &y); G[x].push_back(y); in[y]++; } if (topSort(n,m) { for (int i = 1; i <= n; i++) printf("%d ", path[i]); printf("\n"); } else printf("No topology sequence exists.") } return0; }