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

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

题目描述

输入样例

复制代码
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;
}
相关推荐
散峰而望1 天前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
自然常数e1 天前
深入理解指针(1)
c语言·算法·visual studio
WWZZ20251 天前
快速上手大模型:深度学习13(文本预处理、语言模型、RNN、GRU、LSTM、seq2seq)
人工智能·深度学习·算法·语言模型·自然语言处理·大模型·具身智能
Christo31 天前
AAAI-2024《Multi-Class Support Vector Machine with Maximizing Minimum Margin》
人工智能·算法·机器学习·支持向量机·数据挖掘
元亓亓亓1 天前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
司铭鸿1 天前
化学式解析的算法之美:从原子计数到栈的巧妙运用
linux·运维·服务器·算法·动态规划·代理模式·哈希算法
ekprada1 天前
DAY 18 推断聚类后簇的类型
算法·机器学习·支持向量机
生信大表哥1 天前
Python单细胞分析-基于leiden算法的降维聚类
linux·python·算法·生信·数信院生信服务器·生信云服务器
玫瑰花店1 天前
万字C++中锁机制和内存序详解
开发语言·c++·算法
Elias不吃糖1 天前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode