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

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

题目描述

输入样例

复制代码
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;
}
相关推荐
唯唯qwe-5 分钟前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄20 分钟前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
来深圳36 分钟前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang1 小时前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
hetao17338371 小时前
2025-12-21~22 hetao1733837的刷题笔记
c++·笔记·算法
醒过来摸鱼1 小时前
递归三种分类方法
算法
炽烈小老头2 小时前
【每天学习一点算法 2025/12/22】将有序数组转换为二叉搜索树
学习·算法
jghhh012 小时前
POCS(凸集投影)算法解决部分k空间数据缺失导致吉布斯伪影
算法
罗湖老棍子2 小时前
最小函数值(minval)(信息学奥赛一本通- P1370)
数据结构·c++·算法··优先队列·
LYFlied2 小时前
【每日算法】LeetCode 4. 寻找两个正序数组的中位数
算法·leetcode·面试·职场和发展