图论应用——拓扑排序

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

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;
}
相关推荐
qq_4542450316 小时前
GraphFoundation动态更新图
架构·c#·图论
Rhystt16 小时前
代码随想录算法训练营第六十天|多余的边?从基础到进阶!
开发语言·c++·算法·图论
flying_131416 小时前
图神经网络分享系列-HAN(Heterogeneous Graph Attention Network)(二)
深度学习·神经网络·tensorflow·图论·图神经网络·代码实战·han
kronos.荒2 天前
图论之腐烂橘子_BFS(python)
python·图论·bfs
kronos.荒3 天前
图论之岛屿数量(python)
python·图论
cpp_25014 天前
P8395 [CCC 2022 S1] Good Fours and Good Fives
数据结构·c++·算法·动态规划·图论·题解·洛谷
乐观勇敢坚强的老彭4 天前
c++图论
开发语言·c++·图论
不染尘.5 天前
欧拉路径算法
开发语言·数据结构·c++·算法·图论
ab1515176 天前
3.23完成进阶45、84,二刷基础132、129
算法·深度优先·图论
jing-ya6 天前
day 60 图论part11
java·数据结构·算法·图论