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.

60 lines
1.6 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = N << 1;
int n, m; // 点数,边数
int din[N]; // d[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;
// 拓扑
bool topsort() {
queue<int> q;
// 扫描所有入度为零的点入队列
for (int i = 1; i <= n; i++)
if (!din[i]) q.push(i);
while (q.size()) {
int u = q.front(); // 队列头
q.pop();
path.push_back(u);
for (int i = h[u]; ~i; i = ne[i]) { // 遍历t的所有出边
int v = e[i];
din[v]--;
if (din[v] == 0) // 入度减1后是不是为0 (前序依赖为0)
q.push(v); // 为0则入队列
}
}
// 如果一共n个结点进入过队列则表示存在拓扑序
return path.size() == n;
}
/*
4 4
1 2
2 3
3 4
4 2
*/
int main() {
// 初始化链式前向星
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--) {
int a, b;
cin >> a >> b;
add(a, b);
din[b]++; // 记录每个结点的入度
}
if (!topsort())
puts("-1");
else {
// 队列次序其实就是拓扑序,这里就充分体现了利用数组模拟队列的优势queue<int>就麻烦了。
for (int i = 0; i < n; i++) printf("%d ", path[i]);
puts(""); // 有向无环图的拓扑序是不唯一的
}
return 0;
}