nasarouf

Topological sort

Feb 21st, 2015
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. //topological sort
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <vector>
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <queue>
  8. using namespace std;
  9.  
  10. #define MAX 1000001
  11. int n,seen[MAX],m,indeg[MAX];
  12. pair<int,int> edges[MAX],*e[MAX];
  13. priority_queue<int,vector<int>,greater<int> > q;
  14.  
  15. int main() {
  16.     int i=0,j,k;
  17.    
  18.     //input
  19.     cin>>n;
  20.     m=0;
  21.     while(n--){
  22.         cin>>k>>i; seen[i]=1;
  23.         while(--k){
  24.             cin>>j; seen[j]=1; indeg[j]++;
  25.             edges[m++]=make_pair(i,j);
  26.             i=j;
  27.         }
  28.     }
  29.     sort(edges,edges+m);
  30.     for (i=m-1; i>=0; i--) e[edges[i].first]=edges+i;
  31.    
  32.     //queue up all 0-indegree nodes. pop, add more, repeat.
  33.     for (i=0; i<=MAX; i++) if (seen[i] && indeg[i]==0) q.push(i);
  34.     int first=1;
  35.     while(!q.empty()){
  36.         if (!first) cout<<" "; first=0;
  37.         i=q.top(); q.pop(); cout<<i;
  38.         for(; e[i] && e[i][0].first==i; e[i]++){
  39.             j=e[i][0].second;
  40.             if (--indeg[j]==0) q.push(j);
  41.         }
  42.     }
  43.     cout<<endl;
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment