fork download
  1. #include<bits/stdc++.h>
  2.  
  3. #define ll long long
  4. #define pp push_back
  5. #define endl '\n'
  6. #define all(x) x.begin(),x.end()
  7. #define ld long double
  8. #define PI acos(-1)
  9. #define ones(x) __builtin_popcountll(x)
  10. //#define int ll
  11.  
  12. using namespace std;
  13.  
  14. void Drakon() {
  15. ios_base::sync_with_stdio(false);
  16. cin.tie(nullptr);
  17. cout.tie(nullptr);
  18. #ifdef Clion
  19. freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
  20. #endif
  21. }
  22.  
  23. unsigned long long inf = 1e10;
  24. const double EPS = 1e-6;
  25. const int MOD = 1000000007, N = 1e5 + 5, LOG = 25;
  26.  
  27. ll mul(const ll &a, const ll &b) {
  28. return (a % MOD + MOD) * (b % MOD + MOD) % MOD;
  29. }
  30.  
  31. ll add(const ll &a, const ll &b) {
  32. return (a + b + 2 * MOD) % MOD;
  33. }
  34.  
  35. ll pw(ll x, ll y) {
  36. ll ret = 1;
  37. while (y > 0) {
  38. if (y % 2 == 0) {
  39. x = mul(x, x);
  40. y = y / 2;
  41. } else {
  42. ret = mul(ret, x);
  43. y = y - 1;
  44. }
  45. }
  46. return ret;
  47. }
  48.  
  49. int n, m, in[N];
  50. vector<int> adj[N];
  51.  
  52. void topo() {
  53. queue<int> q;
  54. for (int i = 0; i < n; ++i) {
  55. if(in[i] == 0) q.push(i);
  56. }
  57. vector<int> ans;
  58. while (!q.empty()) {
  59. int u = q.front();
  60. q.pop();
  61. ans.push_back(u);
  62. for(auto v : adj[u]) {
  63. in[v] --;
  64. if(in[v] == 0) q.push(v);
  65. }
  66. }
  67.  
  68. if(ans.size() != n) {
  69. cout << -1 << endl;
  70. return;
  71. }
  72. for(auto x : ans) cout << x + 1 << ' ';
  73. cout << endl;
  74. }
  75.  
  76. void solve() {
  77. cin >> n >> m;
  78. for (int i = 0; i < n; ++i) {
  79. adj[i].clear();
  80. in[i] = 0;
  81. }
  82. for (int i = 0; i < m; ++i) {
  83. int u, v;
  84. cin >> u >> v;
  85. u--, v--;
  86. adj[u].push_back(v);
  87. in[v] ++;
  88. }
  89. topo();
  90. }
  91.  
  92. signed main() {
  93. Drakon();
  94. int t = 1;
  95. cin >> t;
  96. while (t--) {
  97. solve();
  98. }
  99. }
Success #stdin #stdout 0.01s 5868KB
stdin
Standard input is empty
stdout