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.

57 lines
1.1 KiB

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, M = N << 1;
int n, m, ans[N], al;
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 topsort() {
priority_queue<int> q;
for (int i = 1; i <= n; i++)
if (in[i] == 0) q.push(i);
while (q.size()) {
int u = q.top();
q.pop();
ans[al++] = u;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
in[j]--;
if (in[j] == 0) q.push(j);
}
}
}
void solve() {
cin >> n >> m;
al = 0, idx = 0;
memset(h, -1, sizeof h);
while (m--) {
int u, v;
cin >> u >> v;
add(v, u);
in[u]++;
}
topsort();
for (int i = al - 1; i >= 0; i--) {
cout << ans[i];
if (i != 0)
cout << ' ';
else
cout << endl;
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int T;
cin >> T;
while (T--) solve();
return 0;
}