Files
python/TangDou/AcWing/CheckCircle/HDU3342【BFS判环】.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

40 lines
1.2 KiB
C++
Raw 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;
const int N = 1e3 + 10, M = N << 1;
int ind[N];
int n, m;
//邻接表
int e[M], h[N], idx, ne[M];
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int q[N];
int main() {
while (~scanf("%d %d", &n, &m) && n) {
memset(ind, 0, sizeof(ind));
memset(h, -1, sizeof h);
idx = 0;
for (int i = 1; i <= m; i++) {
int a, b;
scanf("%d %d", &a, &b);
add(a, b);
ind[b]++; //记录入度
}
int hh = 0, tt = -1;
for (int i = 0; i < n; i++)
if (ind[i] == 0) q[++tt] = i; //入度为0的入队列
while (hh <= tt) {
int u = q[hh++];
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
ind[j]--; //拓扑模拟减去边,入度-1
if (ind[j] == 0) q[++tt] = j; //如果入度为0,则此节点入队列
}
}
//检查入过队列的节点个数是不是n个,相等则无环
hh == n ? puts("YES") : puts("NO");
}
return 0;
}