思路
这题比较简单一个裸的拓扑排序模板题,只要有拓扑序生成关系就一定正确。
#include <iostream>
#include <cstring>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 105;
struct edge{
int to;
int next;
}e[maxn];
int head[maxn];
int s[maxn];
int cnt,n,m;
queue<int>q;
void clear_set()
{
cnt = 0;
memset(head,-1,sizeof(head));
memset(s,0,sizeof(s));
while(!q.empty()) q.pop();
}
void addedge(int x,int y)
{
e[cnt].to = y;
e[cnt].next = head[x];
head[x] = cnt++;
}
void topsort()
{
for(int i = 0;i < n;i++){
if(s[i] == 0){
q.push(i);
}
}
int k = 0;
while(!q.empty()){
int p = q.front();
k++;
q.pop();
for(int i = head[p];~i;i = e[i].next){
edge t = e[i];
if(--s[t.to] == 0){
q.push(t.to);
s[t.to] = -1;
}
}
}
if(k == n){
printf("YES\n");
}
else{
printf("NO\n");
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
if(n + m == 0){
break;
}
clear_set();
while(m--){
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);s[y]++;
}
topsort();
}
return 0;
}
愿你走出半生,归来仍是少年~