Advertisement
Nita_Cristian

TopSort

Jan 26th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n, m, pasi, sume[100005], bifa[100005];
  6. vector<int> c, l[100005];
  7.  
  8. void topsort(priority_queue<int>q)
  9. {
  10.     for(int i = 1; i <= n; i++)
  11.     {
  12.         if(!sume[i] && !bifa[i])
  13.         {
  14.             q.push(-i);
  15.             bifa[i] = 1;
  16.         }
  17.     }
  18.     while(!q.empty())
  19.     {
  20.         int e = -q.top();
  21.         q.pop();
  22.         cout << e << ' ';
  23.         for(const int it : l[e])
  24.         {
  25.             sume[it]--;
  26.             if(sume[it] == 0)
  27.                 q.push(-it);
  28.         }
  29.     }
  30. }
  31.  
  32. int main()
  33. {
  34.     cin >> n >> m;
  35.     priority_queue<int>q;
  36.     pasi = n;
  37.     for(int i = 1; i <= m; i++)
  38.     {
  39.         int x, y;
  40.         cin >> x >> y;
  41.         l[x].push_back(y);
  42.         sume[y]++;
  43.     }
  44.     topsort(q);
  45.     return 0;
  46. }
  47.  
  48. ////////////////////////////////////////////
  49. #include <bits/stdc++.h>
  50.  
  51. using namespace std;
  52.  
  53. ifstream fin("sortaret.in");
  54. ofstream fout("sortaret.out");
  55.  
  56. vector<int>l[500001];
  57. bitset<500001>bifa;
  58. int n, m, i, j, suma[500001], pas;
  59. queue<int>q;
  60. void topSort()
  61. {
  62.     while(pas)
  63.     {
  64.         for(int i = 1; i <= n; i++)
  65.         {
  66.             if(!suma[i] && !bifa[i])
  67.             {
  68.                 fout << i << ' ';
  69.                 pas--;
  70.                 bifa[i] = 1;
  71.                 q.push(i);
  72.             }
  73.         }
  74.         while(!q.empty())
  75.         {
  76.             int i = q.front();
  77.             for(const int it : l[i])
  78.                     suma[it]--;
  79.             q.pop();
  80.         }
  81.     }
  82. }
  83. int main()
  84. {
  85.     fin >> n >> m;
  86.     pas = n;
  87.     for(int i = 1; i <= m; i++)
  88.     {
  89.         int x, y;
  90.         fin >> x >> y;
  91.         l[x].push_back(y);
  92.         suma[y]++;
  93.     }
  94.     topSort();
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement