AcWing 848. 有向图的拓扑序列

#include<iostream>
#include<cmath>
#include<queue>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int n,m,a,b;
int e[N],ne[N],h[N],idx;
int d[N],top[N],cnt=1;//top是拓扑排序的序列,cnt代表top中有多少元素
void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
bool topsort()
{
    queue<int> q;
    int t;
    for(int i=1;i<=n;i++)
        if(d[i]==0) q.push(i);//将所有入度为0的点都加入到队列之中
    while(q.size())
    {
        t=q.front();//每次取出队头
        top[cnt]=t;//加入到拓扑排序之中
        cnt++;//拓扑排序中的元素加1
        q.pop();
        for(int i=h[t];i!=-1;i=ne[i])//遍历t点的出边
        {
            int j=e[i];
            d[j]--;//入度减少
            if(d[j]==0) q.push(j);//如果j的入度为0,加入到队列之中
        }
    }
    if(cnt<n) return 0;
    else return 1;
}
int main()
{
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    memset(h,-1,sizeof h);//邻接表一开始没有装入任何数据,下标就是都是从-1开始的
    cin>>n>>m;
    while(m--)
    {
        cin>>a>>b;
        add(a,b);
        d[b]++;//a到b b的入度++
    }
    if(topsort()==0) cout<<"-1"<<endl;
    else
    {
        for(int i=1;i<=n;i++)
            cout<<top[i]<<" ";
        cout<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vijurria

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值