版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26398495/article/details/82596532
题目链接
题目分析
判断有向图中是否有环
解题思路
邻接表存储有向图;
对图进行拓扑排序,若所有顶点都能输出即无环!
AC程序(C++)
/**********************************
*@ID: 3stone
*@ACM: HDU-3342 Legal or Not
*@Time: 18/9/10
*@IDE: VSCode + clang++
***********************************/
#include<cstdio>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
const int maxn = 110;
int N, M;
int cnt[maxn]; //保存结点的入度
vector<int> Adj[maxn]; //邻接表(结点数太大,不能用邻接矩阵)
//拓扑排序
void topsort() {
priority_queue<int> Q; //用堆实现,每次先输出编号最小的
for(int i = 0; i < N; i++) { //寻找入度为0的顶点
if(cnt[i] == 0)
Q.push(i);
}
int num = 0;
while(!Q.empty()) {
num++;
int v = Q.top();
Q.pop();
for(int i = 0; i < Adj[v].size(); i++){
//删除边,入度-1,判断
if(--cnt[Adj[v][i]] == 0)
Q.push(Adj[v][i]);
}
}//while
if(num == N) printf("YES\n");
else printf("NO\n");
}
/**/
int main() {
int a, b;
while(true) {
scanf("%d %d", &N, &M);
if(N == 0) break;
//初始化 邻接表
for(int i = 0; i < maxn; i++) Adj[i].clear();
fill(cnt, cnt + maxn, 0);
//输入结点偏序
for(int i = 1; i <= M; i++) {
scanf("%d %d", &a, &b);
Adj[b].push_back(a); //邻接表存储
cnt[a]++;
}
topsort(); //拓扑排序
}
system("pause");
return 0;
}