Files
python/TangDou/LuoGuBook/P2661_Bfs_Check_Circle_Prepare.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

57 lines
1.5 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}