'commit'
This commit is contained in:
59
TangDou/CSP-J/J-2023/CaiYaoZhiZhuo.cpp
Normal file
59
TangDou/CSP-J/J-2023/CaiYaoZhiZhuo.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user