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.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 510;
bool g[N][N]; // 邻接矩阵
int in[N]; // 入度
int n, m; // n个顶点m条边
// 小顶堆
priority_queue<int, vector<int>, greater<int>> q;
/*
4 3
1 2
2 3
4 3
1 2 4 3
*/
void toposort() {
// 所有入度为零的节点入队列,是拓扑序的起始节点
for (int i = 1; i <= n; i++)
if (in[i] == 0) q.push(i);
int cnt = 0;
while (q.size()) {
int u = q.top();
q.pop();
cnt++; // 又一个节点出队列
// 输出拓扑序
if (cnt != n)
cout << u << " ";
else
cout << u << endl;
for (int i = 1; i <= n; i++)
if (g[u][i]) {
in[i]--;
if (!in[i]) q.push(i);
}
}
}
int main() {
while (cin >> n >> m) {
memset(g, 0, sizeof g);
memset(in, 0, sizeof in);
while (m--) {
int x, y;
cin >> x >> y;
if (g[x][y]) continue; // 防止重边
g[x][y] = 1; // 设置有关联关系
in[y]++; // 入度+1
}
toposort(); // 拓扑序
}
return 0;
}