图论应用——拓扑排序

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

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 天前
最小权顶点覆盖问题和最小权支配集
图论·图搜索算法
旺仔小拳头..1 天前
数据结构(四)————图
图论
点云SLAM2 天前
boost中boost::adjacency_list 与 boost::adjacency_list_traits
数据结构·图论·最大流·boos中图模块·泛型算法·traits 解耦设计·adjacency_list
Bruce_kaizy2 天前
c++图论————最短路之Floyd&Dijkstra算法
c++·算法·图论
xu_yule2 天前
算法基础(图论)—拓扑排序
c++·算法·动态规划·图论·拓扑排序·aov网
Andyshengwx3 天前
图论 最小生成树 MST问题
c++·算法·图论
賬號封禁中miu3 天前
图论之最小生成树
java·数据结构·算法·图论
脑海科技实验室3 天前
Ageing Res Rev:绘制阿尔茨海默病分期进展图:一项利用静息态fMRI和图论的综合性横断面及纵向研究
图论·fmri·阿尔茨海默病
闻缺陷则喜何志丹3 天前
【图论 拓扑排序 贪心 临项交换】P5603 小 C 与桌游 题解|普及+
c++·算法·图论·贪心·拓扑排序·洛谷·临项交换
闻缺陷则喜何志丹3 天前
【图论 BFS染色 并集查找 】P3663 [USACO17FEB] Why Did the Cow Cross the Road III S|普及+
c++·算法·图论·染色法·宽度优先·并集查找