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

60 lines
1.6 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;
#define int long long
const int N = 100010, M = N << 1;
int in[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++;
}
void solve() {
memset(in, 0, sizeof in); // 入度
memset(h, -1, sizeof h); // 初始化链式前向星
idx = 0;
priority_queue<int> q; // 优先队列大顶堆
map<pair<int, int>, int> _map; // 使用红黑树保存已经添加过关系的数,防止出现重边
vector<int> ans;
int n, m;
cin >> n >> m; // n个菜,m个关系
while (m--) {
int x, y;
cin >> x >> y;
if (!_map[{x, y}]) { // 防止重复建边
_map[{x, y}] = 1;
add(y, x); // 反向建图
in[x]++; // 记录入度
}
}
// 入度为零的入队列
for (int i = 1; i <= n; i++)
if (!in[i]) q.push(i);
// Topsort
while (q.size()) {
int u = q.top(); // 序号大的先出来,然后倒序输出
q.pop();
ans.push_back(u); // 记录出队顺序
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
in[j]--;
if (!in[j]) q.push(j);
}
}
if (ans.size() != n)
cout << "Impossible!";
else
for (int i = n - 1; i >= 0; i--) cout << ans[i] << ' ';
cout << endl;
}
signed main() {
int T;
cin >> T;
while (T--) solve();
return 0;
}