You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
5 5
|
|
|
|
|
|
|
|
|
|
1 2
|
|
|
|
|
2 3
|
|
|
|
|
2 5
|
|
|
|
|
3 4
|
|
|
|
|
3 1
|
|
|
|
|
|
|
|
|
|
对比上个例子,添加了一条3->1的边,就成了有向有环图.
|
|
|
|
|
本题,也就不能输出拓扑序了,因为有环图没有拓扑序,拓扑序是针对DAG的。可以判断是否有环。
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
//本代码功能:以bfs判断一个有向图SDG是否有环
|
|
|
|
|
const int N = 1010;
|
|
|
|
|
|
|
|
|
|
int st[N]; //标识是不是已经使用过
|
|
|
|
|
vector<int> edge[N];//邻接表
|
|
|
|
|
int ind[N]; //入度表
|
|
|
|
|
int n; //n个结点
|
|
|
|
|
int m; //m个关系
|
|
|
|
|
queue<int> q; //队列
|
|
|
|
|
vector<int> ans; //ans 为拓扑序列
|
|
|
|
|
int main() {
|
|
|
|
|
//读入,建图
|
|
|
|
|
cin >> n >> m;
|
|
|
|
|
for (int i = 1; i <= m; i++) {
|
|
|
|
|
int x, y;
|
|
|
|
|
cin >> x >> y;
|
|
|
|
|
edge[x].push_back(y);
|
|
|
|
|
ind[y]++;
|
|
|
|
|
}
|
|
|
|
|
for (int i = 1; i <= n; i++) if (ind[i] == 0) q.push(i); //将入度为0的点入队列
|
|
|
|
|
|
|
|
|
|
while (!q.empty()) {
|
|
|
|
|
int p = q.front();
|
|
|
|
|
q.pop(); // 选一个入度为0的点,出队列
|
|
|
|
|
ans.push_back(p);
|
|
|
|
|
for (int i = 0; i < edge[p].size(); i++) {
|
|
|
|
|
int y = edge[p][i];
|
|
|
|
|
ind[y]--;
|
|
|
|
|
if (ind[y] == 0) q.push(y);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (ans.size() == n) {
|
|
|
|
|
for (int i = 0; i < ans.size(); i++)
|
|
|
|
|
printf("%d ", ans[i]);
|
|
|
|
|
printf("\n");
|
|
|
|
|
} else printf("No Answer!\n"); // ans 中的长度与n不相等,就说明无拓扑序列
|
|
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
|
}
|