bfs应用---拓扑排序

含义

所有点都是从小编号指向大编号
是一个有序无环图
检查时遍历所有入度0的节点并删除与之相关的连线

模板

有向图的拓扑序列

#include<iostream>
#include<cstring>

using namespace std;

const int N = 100010;

int e[N],ne[N],h[N],idx;
int q[N],d[N];
int n,m;

void add(int a,int b){
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}

bool chk(){
    int tt = -1,hh = 0;

    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];
            d[j] --;
            if(!d[j]) q[++ tt] = j;
        }
    }

    return tt == n - 1;
}

int main(){
    cin >> n >> m;

    memset(h,-1,sizeof h);

    while(m --){
        int a,b;
        cin >> a >> b;

        add(a,b);
        d[b] ++;
    }

    if(chk()) for(int i = 0;i < n;i ++) cout << q[i] << ' ';
    else cout << -1;
}

posted @ 2021-07-22 07:48  Xuuxxi  阅读(41)  评论(0编辑  收藏  举报