水题不解释
拓扑排序判断有无环
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<ctype.h>
#include<queue>
using namespace std;
struct node
{
int u,v,next;
} edge[1100000];
int head[1000000],vis[200000],rudu[200000],cnt,n;
void add(int u,int v)
{
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void topu()
{
memset(vis,0,sizeof(vis));
int s=0;
queue<int>q;
while(!q.empty())
q.pop();
for(int i=1; i<=n; i++)
{
if(rudu[i]==0)
{
q.push(i);
vis[i]=1;
}
}
while(!q.empty())
{
int u=q.front();
q.pop();
s++;
for(int i=head[u]; i!=-1; i=edge[i].next)
{
if(rudu[edge[i].v])
{
rudu[edge[i].v]--;
}
if(rudu[edge[i].v]==0&&vis[edge[i].v]==0)
{
q.push(edge[i].v);
vis[edge[i].v]=1;
}
}
}
if(s==n)
printf("YES\n");
else
printf("NO\n");
}
int main()
{
int m;
while(~scanf("%d %d",&n,&m))
{
cnt=0;
memset(rudu,0,sizeof(rudu));
memset(head,-1,sizeof(head));
for(int i=0; i<m; i++)
{
int u,v;
scanf("%d %d",&u,&v);
add(u,v);
rudu[v]++;
}
topu();
}
return 0;
}