图论应用——拓扑排序

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

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;
}
相关推荐
前端小L3 天前
图论专题(二):“关系”的焦点——一眼找出「星型图的中心节点」
数据结构·算法·深度优先·图论·宽度优先
Algor_pro_king_John3 天前
模板ACM
算法·图论
前端小L3 天前
图论专题(六):“隐式图”的登场!DFS/BFS 攻克「岛屿数量」
数据结构·算法·深度优先·图论·宽度优先
-大头.3 天前
Python数据结构之旅:09-图论基础——连接万物的网络
数据结构·图论
前端小L3 天前
图论专题(五):图遍历的“终极考验”——深度「克隆图」
数据结构·算法·深度优先·图论·宽度优先
前端小L4 天前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿4 天前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
im_AMBER5 天前
数据结构 11 图
数据结构·笔记·学习·图论
沧澜sincerely5 天前
BFS & 图论【各种题型+对应LeetCode习题练习】
leetcode·图论·广度优先
hansang_IR10 天前
【题解】洛谷 P1477 [NOI2008] 假面舞会 [思维 + 图论]
c++·算法·图论·思维