【代码】
拓扑排序模板
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
#define f(i,n) for(int i=1;i<=(n);i++)
#define ll long long
#define INF 1<<30
#define N 100010
#define M 200010
int n,m;
int read()
{
int x=0,f=1;char c=getchar();
while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while( isdigit(c)){x=x*10+c-'0';c=getchar();}
return x*f;
}
struct xj
{
int y;
int next;
}map[2*M];
int cnt;
int head[N];
void add_edge(int u,int v)
{
map[++cnt].y=v;
map[cnt].next=head[u];
head[u]=cnt;
}
queue<int> q;
int rd[N],ans[N],vis[N];
void tp()
{
f(i,n)if(!rd[i])q.push(i);
while(!q.empty())
{
int f=q.front();
printf("%d ",f);
q.pop();
vis[f]=1;
for(int i=head[f];i;i=map[i].next)
{
if(vis[map[i].y])continue;
rd[map[i].y]--;
if(!rd[map[i].y])q.push(map[i].y);
}
}
}
int main()
{
n=read();
m=read();
int u,v;
f(i,m)
{
u=read();
v=read();
rd[v]++;
add_edge(u,v);
}
tp();
}