AcWing 848. 有向图的拓扑序列
原题链接
简单
作者:
SayYong
,
2024-09-28 18:39:52
,
所有人可见
,
阅读 1
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 100010;
int h[N], e[N * 2], ne[N * 2], idx;
int d[N], top[N], cnt = 0;
int n, m;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topSort() {
// 定义队列 + 入队
queue<int> q;
for (int i = 1; i <= n; i++)
if (d[i] == 0) q.push(i);
// cout << "while循环前测试" << endl;
while (q.size()) {
int t = q.front();
q.pop();
top[cnt++] = t;
for (int i = h[t]; i != -1; i = ne[i]) {
// 关键代码
int j = e[i]; // 取出节点
d[j]--;
if (d[j] == 0) q.push(j);
}
}
if (cnt == n) return true;
else return false;
}
int main(void)
{
cin >> n >> m;
memset(h, -1, sizeof (h));
// 建立有向图
while (m--) {
int a, b;
cin >> a >> b;
add(a, b);
d[b]++;
}
if (topSort())
for (int i = 0; i < cnt; i++) cout << top[i] << ' ';
else
cout << -1 << endl;
return 0;
}