有向图的拓扑序列

思路

拓扑排序其实就是一个BFS的搜索过程,注意如何使用队列来维护的,另外,还要注意一下图的存储方式

const int N = 1e5 + 10;//数据范围,一般边数组要比点数组多开一倍空间
int n, m;//点数和边数
int h[N], e[N], ne[N], idx = 0;

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);//记得初始化h数组,不然会TLE
    for(int i = 0; i < m; i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
}

代码

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int h[N], e[N], ne[N], idx = 0;
int d[N];
queue<int> q, res;
void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topsort()
{
    for(int i = 1; i <= n; i++)
    {
        if(d[i] == 0) q.push(i);
    }
    while(q.size())
    {
        auto t = q.front();res.push(t);q.pop();
        
        for(int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            d[j]--;
            if(d[j] == 0) q.push(j);
        }
    }
    if(res.size() == n) return true;
    else return false;
}
int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for(int i = 0; i < m; i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b);
        d[b]++;
    }
    
    if(topsort())
    {
        while(res.size()) 
        {
            cout << res.front() <<  " ";
            res.pop();
        }
        puts("");
    }
    else puts("-1");
    
    return 0;
}
全部评论

相关推荐

07-08 13:48
门头沟学院 C++
点赞 评论 收藏
分享
嵐jlu:我是山川🐔里🐔🧱的,阿里系简历全过; 你这简历一看就还是半成品啊,没有荣誉经历奖项什么的吗?
投递阿里巴巴集团等公司10个岗位
点赞 评论 收藏
分享
白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
投了多少份简历才上岸
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
Steven267:这不喷回去?花钱是大爷,记住这个道理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务