acwing 848 有向图的拓扑序列 (求图是否有环)

题面

在这里插入图片描述

题解

在这里插入图片描述

==我们观察可以发现,对于一个有环图,这个环上的所有点入度都是不为0的,==根据这个性质,我们就可以让所有入度为0的点入队,然后再删除i->j的边(其实就是让d[j]–),当d[j]为0时,继续入队,这样如果没有环的话,我们可以让所有点都入队,最后只需要判断所有点是否已经都入队完成了,如果没有入队,说明存在环,当然,队列中的顺序就是拓扑序(拓扑序不唯一)

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 1e5 + 10;

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;
    //如果入度为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];
            //删除i->j的边(入度-1),如果入度为0,加入队列
            if (--d[j] == 0) q[++tt] = j;
        }
    }

    return tt == n - 1;
}

int main() {
    
    

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    memset(h, -1, sizeof h);

    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
    
    
        int a, b;
        cin >> a >> b;
        d[b]++;
        add(a, b);
    }

    if (topsort()) {
    
    
        for (int i = 0; i < n; i++) {
    
    
            cout << q[i] << " ";
        }
        cout << endl;
    } else {
    
    
        cout << -1 << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/114404863
今日推荐