拓扑排序模板(无废话)

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
int cnt,head[10001],rd[10001],n,m;
struct Edge
{
    int to,next;
}a[20001];
void AddEdge(int start,int end)
{
    cnt++;
    a[cnt].to=end;
    a[cnt].next=head[start];
    head[start]=cnt;
    return;
}
void Topsort()
{
    queue<int>q;
    for(int i=1;i<=n;i++)
    {
        if(rd[i]==0) q.push(i);
    }
    while(!q.empty())
    {
        int node=q.front();
        cout<<node<<" ";
        q.pop();
        rd[node]=-1;
        for(int i=head[node];i;i=a[i].next)
        {
            rd[a[i].to]--;
            if(rd[a[i].to]==0) q.push(a[i].to);
        }
    }
    return;
}
int main()
{
    int x,y;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y;
        AddEdge(x,y);
        rd[y]++;
    }
    Topsort();
    return 0;
 }