图论应用——拓扑排序

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

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;
}
相关推荐
leoufung1 天前
组合问题:为什么用start避免重复
算法·深度优先·图论
mmz12072 天前
前缀和问题(c++)
c++·算法·图论
剪一朵云爱着3 天前
PAT 1131 Subway Map
算法·pat考试·图论
hakertop3 天前
如何基于C#读取.dot图论文件并和QuickGraph联动
数据库·c#·图论
烛衔溟3 天前
C语言图论:无向图基础
c语言·数据结构·图论·无向图
小李小李快乐不已3 天前
图论理论基础(5)
数据结构·c++·算法·机器学习·动态规划·图论
烛衔溟3 天前
C语言图论:有向图基础
c语言·数据结构·图论·有向图
zheyutao3 天前
割点和桥
算法·图论
代码雕刻家4 天前
1.9.课设实验-数据结构-图-校园跑最短路径
c语言·数据结构·算法·图论
小李小李快乐不已4 天前
图论理论基础(4)
c++·算法·图论·迭代加深