题目链接:HDU3342
题目大意:给一个n个点m条边的有向关系图,问这图中是否存在环,即判断是否是DAG 。
解题思路:拓扑排序判环模板题
AC代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>
using namespace std;
const int maxn = (int)1e2+5;
int book[maxn],n,m,v,u;
vector<int> Vertex[maxn];
queue<int> Q;
bool tuopu () {
for (int i = 0; i < n; i++) {
if(book[i] == 0) {
Q.push(i);
}
}
while (!Q.empty()) {
u = Q.front();
Q.pop();
Vertex[n].push_back(u);
for (vector<int>::iterator it = Vertex[u].begin(); it != Vertex[u].end(); it++) {
book[*it]--;
if(book[*it] == 0) {
Q.push(*it);
}
}
}
if(Vertex[n].size() == n) {
return true;
}
return false;
}
int main() {
while (~scanf("%d%d",&n,&m) && n+m) {
for (int i = 0; i <= n; i++) {
Vertex[i].clear();
}
memset(book,0,sizeof(book));
for (int i = 0; i < m; i++) {
scanf("%d%d",&u,&v);
Vertex[u].push_back(v);
book[v]++;
}
while(!Q.empty()) {
Q.pop();
}
if(tuopu()) {
puts("YES");
}else {
puts("NO");
}
}
return 0;
}
小记:
2018年最后一篇。