Advertisement
alexOloieri

InfoGIM 17.04.2021 Sortare topologica

Apr 17th, 2021
1,643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <queue>
  4. #define NMAX 100005
  5. using namespace std;
  6. ifstream fin("topsort.in");
  7. ofstream fout("topsort.out");
  8.  
  9. int n, m;
  10. int x, y;
  11. int gi[NMAX];
  12. vector<int> G[NMAX];
  13. queue<int> Q;
  14.  
  15. int main()
  16. {
  17.     fin >> n >> m;
  18.     for (int i=1;i<=m;++i) {
  19.         fin >> x >> y;
  20.         G[x].push_back(y);
  21.         ++gi[y];
  22.     }
  23.     for (int i=1;i<=n;++i) {
  24.         if (gi[i] == 0) {
  25.             Q.push(i);
  26.         }
  27.     }
  28.     while (!Q.empty()) {
  29.         int nodCurent = Q.front();
  30.         Q.pop();
  31.         // Stim sigur ca nodul "nodCurent" are gradul interior 0
  32.         fout << nodCurent << ' ';
  33.         int sz = G[nodCurent].size();
  34.         for (int i=0;i<sz;++i) {
  35.             int vecin = G[nodCurent][i];
  36.             --gi[vecin];
  37.             if (gi[vecin] == 0) {
  38.                 // Toate nodurile care aveau arce ce intrau in acest nod au fost puse
  39.                 // In sortarea topologica, nodul "vecin" poate fi adaugat si el
  40.                 Q.push(vecin);
  41.             }
  42.         }
  43.     }
  44.     fin.close();
  45.     fout.close();
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement