图论应用——拓扑排序

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

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;
}
相关推荐
图灵科竞社资讯组11 小时前
图论基础:图存+记忆化搜索
算法·图论
啊阿狸不会拉杆17 小时前
数据结构-图
java·c语言·数据结构·c++·python·算法·图论
rgb2gray21 小时前
描述城市出行需求模式的复杂网络视角:大规模起点-目的地需求网络的图论分析
网络·图论
ん贤1 天前
图论算法体系:并查集、生成树、排序与路径搜索全解析
图论
_安晓1 天前
数据结构 -- 图的应用(一)
数据结构·算法·图论
奶油泡芙shi_caicai2 天前
算法题-图论
算法·图论
_extraordinary_3 天前
数据结构图论基础知识(一)
数据结构·图论
How_doyou_do3 天前
P5839-图论-Floyd算法
数据结构·算法·图论
callJJ4 天前
Floyd算法求解最短路径问题——从零开始的图论讲解(3)
java·算法·动态规划·图论·dijkstra算法·floyd算法·最短路径问题
君义_noip4 天前
信息学奥赛一本通 1504:【例 1】Word Rings | 洛谷 SP2885 WORDRING - Word Rings
c++·算法·图论·信息学奥赛