Advertisement
hadiuzzaman65

Topological sort

Oct 23rd, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. // Note: topological sort result is not unique . so don't worried
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <iterator>
  6. #include <queue>
  7. using namespace std;
  8.  
  9.  
  10. void topologicalsort(vector<int>v[],int n)
  11. {
  12.     vector<int>indegree(n,0);
  13.     vector<int>::iterator it;
  14.  
  15.     for(int i=0; i<n; i++)
  16.     {
  17.         for(it=v[i].begin(); it !=v[i].end(); it++)
  18.         {
  19.             indegree[*it]++;
  20.         }
  21.     }
  22.  
  23.  
  24.     queue<int>q;
  25.     vector<int>result;
  26.  
  27.     for(int i=0; i<n; i++)
  28.     {
  29.         if(indegree[i]==0)
  30.             q.push(i);
  31.     }
  32.     int c=0;
  33.     while(!q.empty())
  34.     {
  35.         int m=q.front();
  36.         result.push_back(m);
  37.         q.pop();
  38.  
  39.         for(it=v[m].begin(); it !=v[m].end(); it++)
  40.         {
  41.             --indegree[*it];
  42.  
  43.             if(indegree[*it]==0)
  44.             {
  45.                 q.push(*it);
  46.             }
  47.             c++;
  48.  
  49.         }
  50.  
  51.  
  52.     }
  53.     if(c==n)
  54.     {
  55.         cout<< "Top sort: ";
  56.  
  57.         for(int i=0; i<result.size(); i++)
  58.             cout<<result[i]<< " ";
  59.         cout<<endl;
  60.     }
  61.     else
  62.     {
  63.       cout<< "The graph is not a DAG"<<endl;
  64.       return ;
  65.     }
  66.  
  67.  
  68.  
  69. }
  70.  
  71. int main()
  72. {
  73.  
  74.     int node,edge;
  75.  
  76.     cout<< "Number of the nodes and edges: ";
  77.     cin>>node>>edge;
  78.     vector<int>v[node];
  79.  
  80.     cout<< "Enter edge information(u,v)"<<endl;
  81.     for(int i=0; i<edge; i++)
  82.     {
  83.         int m,n;
  84.         cin>>m>>n;
  85.         v[m].push_back(n);
  86.     }
  87.     topologicalsort(v,node);
  88.  
  89.     return 0;
  90. }
  91.  
  92. /*
  93. 4 4
  94. 0 1
  95. 2 0
  96. 2 1
  97. 2 3
  98.  
  99. 4 4
  100. 0 1
  101. 1 2
  102. 2 1
  103. 2 3
  104.  
  105. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement