You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.1 KiB
48 lines
1.1 KiB
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
const int N = 110, M = N * N;
|
|
|
|
int n;
|
|
int din[N];
|
|
// 链式前向星
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
void add(int a, int b, int c = 0) {
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
}
|
|
vector<int> path;
|
|
// 如果要按字典序输出拓扑序,那么使用小顶堆即可
|
|
void topsort() {
|
|
priority_queue<int, vector<int>, greater<int>> q;
|
|
// 所有入度为0的入队列
|
|
for (int i = 1; i <= n; i++)
|
|
if (din[i] == 0) q.push(i);
|
|
|
|
while (q.size()) {
|
|
int u = q.top();
|
|
q.pop();
|
|
path.push_back(u);
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int v = e[i];
|
|
din[v]--;
|
|
if (din[v] == 0) q.push(v);
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
memset(h, -1, sizeof h);
|
|
cin >> n;
|
|
for (int a = 1; a <= n; a++) {
|
|
int b;
|
|
while (cin >> b, b) {
|
|
add(a, b);
|
|
din[b]++; // 入度++
|
|
}
|
|
}
|
|
// 拓扑序
|
|
topsort();
|
|
// 输出任意一组拓扑序
|
|
for (int i = 0; i < n; i++) printf("%d ", path[i]);
|
|
return 0;
|
|
} |