TopologicalSort.cpp 555 B

1234567891011121314151617181920212223
  1. const int SIZE = 5000;
  2. int deg[SIZE];
  3. int ord[SIZE]; // ord start with 1
  4. void TopSort(vector<int> G[], int n) {
  5. memset(deg, 0, sizeof(deg));
  6. memset(ord, 0, sizeof(ord));
  7. fin(i, n) for(int j : G[i]) deg[j]++;
  8. queue<int> Q;
  9. fin(i, n) if(!deg[i]) {
  10. Q.push(i);
  11. ord[i] = 1;
  12. }
  13. while(!Q.empty()) {
  14. int i = Q.front(); Q.pop();
  15. for(int j : G[i]) {
  16. deg[j]--;
  17. if(!deg[j]) {
  18. Q.push(j);
  19. ord[j] = ord[i] + 1;
  20. }
  21. }
  22. }
  23. }