拓扑排序

家族树

\(拓扑排序模板\)

\(拓扑排序基于bfs\)

#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 110, M = N * N / 2;
int n;
int h[N], e[M], ne[M], idx;
int q[N];
int d[N];

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

void 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; i = ne[i]) {
            int j = e[i];
            if (--d[j] == 0) q[++tt] = j;
        }
    }
}
 
int main() {
    IO;
    cin >> n;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= n; ++i) {
        int son;
        while (cin >> son, son) {
            add(i, son);
            d[son]++;
        }
    }
    topsort();
    for (int i = 0; i < n; ++i) cout << q[i] << " ";
    return 0;
}

posted @ 2021-02-25 17:12  phr2000  阅读(53)  评论(0编辑  收藏  举报