搜索与图论:有向图的拓扑序列

搜索与图论:有向图的拓扑序列

题目描述

输入样例

复制代码
3 3
1 2
2 3
1 3

输出样例

···

1 2 3

···

参考代码

cpp 复制代码
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n, m;
int h[N], e[N], ne[N], idx;
int d[N], q[N];

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

bool topsort()
{
    int hh = 0, tt = -1;
    
    for (int i = 1; i <= n; i++)
        if (!d[i])
            q[++tt] = i;
    
    while (hh <= tt)
    {
        int t = q[hh ++];
        
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int j = e[i];
            d[j]--;
            if (d[j] == 0) q[++ tt] = j;
        }
    }
    
    return tt == n - 1;
}

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())
    {
        for (int i = 0; i < n; i++) printf("%d ", q[i]);
        puts("");
    }
    
    else puts("-1");
    
    return 0;
}
相关推荐
KingRumn4 小时前
Linux信号之标准信号与实时信号
linux·算法
源代码•宸7 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
2301_800256118 小时前
地理空间数据库中的CPU 和 I/O 开销
数据库·算法·oracle
一个不知名程序员www8 小时前
算法学习入门---结构体和类(C++)
c++·算法
XFF不秃头11 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
王老师青少年编程11 小时前
csp信奥赛C++标准模板库STL案例应用3
c++·算法·stl·csp·信奥赛·lower_bound·标准模版库
有为少年12 小时前
Welford 算法 | 优雅地计算海量数据的均值与方差
人工智能·深度学习·神经网络·学习·算法·机器学习·均值算法
Ven%12 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
山楂树の12 小时前
爬楼梯(动态规划)
算法·动态规划