图论应用——拓扑排序

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

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 天前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
_Coin_-1 天前
算法训练营DAY58 第十一章:图论part08
数据结构·算法·图论
闪电麦坤954 天前
数据结构:图的表示 (Representation of Graphs)
数据结构·算法·图论
BlackPercy4 天前
【图论】Graphs.jl 最小生成树算法文档
算法·图论
SuperCandyXu5 天前
洛谷 P3128 [USACO15DEC] Max Flow P -普及+/提高
c++·算法·图论·洛谷
zc.ovo5 天前
牛子图论1(二分图+连通性)
数据结构·c++·算法·深度优先·图论
ltrbless6 天前
最小生成树算法详解
算法·排序算法·图论
love you joyfully6 天前
图论简介与图神经网络(Dijkstra算法,图卷积网络GCN实战)
人工智能·深度学习·神经网络·算法·贪心算法·图论
YA10JUN7 天前
数据结构基础--最小生成树
数据结构·算法·图论
啊我不会诶10 天前
【图论】最短路算法
算法·图论