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

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

题目描述

输入样例

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;
}
相关推荐
浅念同学3 小时前
算法-常见数据结构设计
java·数据结构·算法
UndefindX3 小时前
PAT甲级1006 :Sign In and Sign Out
数据结构·算法
T风呤6 小时前
学生管理系统(通过顺序表,获取连续堆区空间实现)
算法
stackY、6 小时前
【Linux】:程序地址空间
linux·算法
心死翼未伤7 小时前
【MySQL基础篇】多表查询
android·数据结构·数据库·mysql·算法
Orion嵌入式随想录8 小时前
算法训练 | 图论Part1 | 98.所有可达路径
算法·深度优先·图论
西西,正在减肥8 小时前
【leetcode52-55图论、56-63回溯】
算法
Beast Cheng8 小时前
07-7.1.1 查找的基本概念
数据结构·笔记·考研·算法·学习方法
DogDaoDao8 小时前
LeetCode 算法:二叉树中的最大路径和 c++
c++·算法·leetcode·二叉树·二叉树路径
望舒_2338 小时前
【算法专题】双指针算法
算法