1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <bits/stdc++.h> const int N = 1e5 + 100; int n, m; struct Edge{ int ne, ver; } e[N << 1]; int h[N], idx = 0, du[N]; std::priority_queue<int> q; std::vector<int> ans; void add(int x, int y){ e[idx] = {h[x], y}, h[x] = idx++; } void topu() { for (int i = 1; i <= n; ++i) if (!du[i]) q.push(i); while (!q.empty()) { int x = q.top(); q.pop(); ans.push_back(x); for (int i = h[x], y; ~i; i = e[i].ne) { --du[y = e[i].ver]; if (!du[y]) q.push(y); } } } int main() { int T; for (scanf("%d", &T); T--; ) { scanf("%d %d", &n, &m); memset(h + 1, -1, n << 2), idx = 0; memset(du + 1, 0, n << 2), ans.clear(); for (int i = 1, u, v; i <= m; ++i) { scanf("%d %d", &u, &v); add(v, u), ++du[u]; } topu(); bool f = true; for (int i = 1; i <= n && f; ++i) if (du[i]) f = false; if (!f) printf("Impossible!"); else for (int i = ans.size() - 1; ~i; --i) printf("%d ", ans[i]); puts(""); } return 0; }
|