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.
python/TangDou/LuoGuBook/P2661_Bfs_Check_Circle_Prep...

57 lines
1.5 KiB

2 years ago
#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;
}