Advertisement
nasarouf

Topological sort

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