图论应用——拓扑排序

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

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;
}
相关推荐
每天要多喝水2 天前
图论Day39:孤岛题目
算法·深度优先·图论
仟濹2 天前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
仰泳的熊猫2 天前
蓝桥杯算法提高VIP-种树
数据结构·c++·算法·蓝桥杯·深度优先·图论
每天要多喝水3 天前
图论Day38:孤岛基础
算法·深度优先·图论
xsyaaaan3 天前
代码随想录Day43图:图论理论基础_深搜理论基础_98所有可达路径_广搜理论基础
图论
WW_千谷山4_sch4 天前
MYOJ_7789:(洛谷P3388)【模板】割点(割顶)(tarjan算法)
c++·算法·深度优先·图论
WW_千谷山4_sch4 天前
MYOJ_11705:(洛谷P1137)旅行计划(经典拓扑排序)
c++·算法·动态规划·图论
yyy(十一月限定版)4 天前
图论——最小生成树Kruskal算法
算法·图论
yyy(十一月限定版)5 天前
图论——最短路Dijkstra算法
算法·图论
-海绵东东-5 天前
图论——代码篇
算法·深度优先·图论