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.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
const int N = 100010;
|
|
|
|
|
int n, m; // 点数,边数
|
|
|
|
|
int ind[N]; // in[N]:入度,所有入度为零的点,可以排在当前最前面的位置。
|
|
|
|
|
|
|
|
|
|
// 树和图的存储
|
|
|
|
|
int h[N], e[N], ne[N], idx;
|
|
|
|
|
void add(int a, int b) {
|
|
|
|
|
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
|
|
|
|
|
}
|
|
|
|
|
vector<int> path;
|
|
|
|
|
// 拓扑
|
|
|
|
|
bool topsort() {
|
|
|
|
|
queue<int> q;
|
|
|
|
|
// 扫描所有入度为零的点入队列
|
|
|
|
|
for (int i = 1; i <= n; i++)
|
|
|
|
|
if (!ind[i]) {
|
|
|
|
|
q.push(i);
|
|
|
|
|
path.push_back(i);
|
|
|
|
|
}
|
|
|
|
|
while (q.size()) {
|
|
|
|
|
int u = q.front(); // 队列头
|
|
|
|
|
q.pop();
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) { // 遍历t的所有出边
|
|
|
|
|
int v = e[i];
|
|
|
|
|
if (--ind[v] == 0) { // 入度减1后,是不是为0 (前序依赖为0)
|
|
|
|
|
q.push(v); // 为0则入队列
|
|
|
|
|
path.push_back(v);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// 如果一共n个结点进入过队列,则表示存在拓扑序
|
|
|
|
|
return path.size() == n;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
// 初始化为-1
|
|
|
|
|
memset(h, -1, sizeof h);
|
|
|
|
|
cin >> n >> m;
|
|
|
|
|
for (int i = 0; i < m; i++) {
|
|
|
|
|
int a, b;
|
|
|
|
|
cin >> a >> b;
|
|
|
|
|
add(a, b);
|
|
|
|
|
ind[b]++; // 记录每个结点的入度
|
|
|
|
|
}
|
|
|
|
|
if (!topsort())
|
|
|
|
|
puts("-1");
|
|
|
|
|
else {
|
|
|
|
|
for (int i = 0; i < n; i++) printf("%d ", path[i]);
|
|
|
|
|
puts(""); // 有向无环图的拓扑序不唯一
|
|
|
|
|
}
|
|
|
|
|
return 0;
|
|
|
|
|
}
|