图论应用——拓扑排序

拓扑排序的原理和宽度优先搜索差不多

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 100010;
int n,m;
int h[N],e[N],ne[N],idx;
int q[N],d[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];
            if(--d[j]==0)
            {
                q[++tt]=j;
            }
        }
    }
    return tt==n-1;
}

int main(void)
{
    scanf("%d%d", &n,&m);
    memset(h, -1, sizeof h);
    while (m -- )
    {
        int a,b;
        scanf("%d%d",&a,&b);
        add(a,b);
        d[b]++;
    }
    if(topsort())
    {
        for(int i=0;i<n;i++)
            printf("%d ",q[i]);
    }
    else puts("-1");
    return 0;
}
相关推荐
计信金边罗1 天前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
闻缺陷则喜何志丹3 天前
【二分图 图论】P9384 [THUPC 2023 决赛] 着色|普及+
c++·算法·图论·二分图·洛谷
鸽子炖汤3 天前
LRC and VIP
c++·算法·图论
JK0x075 天前
代码随想录算法训练营 Day61 图论ⅩⅠ Floyd A※ 最短路径算法
算法·图论
qq_447429415 天前
数据结构与算法:图论——拓扑排序
linux·c语言·学习·图论
zc.ovo5 天前
图论刷题1
算法·深度优先·图论
珂朵莉MM6 天前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
蒙奇D索大6 天前
【数据结构】图论核心算法解析:深度优先搜索(DFS)的纵深遍历与生成树实战指南
数据结构·算法·深度优先·图论·图搜索算法
ShiinaMashirol6 天前
代码随想录打卡|Day50 图论(拓扑排序精讲 、dijkstra(朴素版)精讲 )
java·图论
JK0x078 天前
代码随想录算法训练营 Day60 图论Ⅹ Bellmen_ford 系列算法
android·算法·图论