Files
python/TangDou/CSP-J/J-2023/HDU1285.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

60 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}