Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. /*  Apply Kahn's algorithm to obtain a topological sorting of the original graph. */
  2. vector<int> topologicalSort(vector<vector<tuple<int,int,int>>> graph)
  3. {
  4.     queue<int> Z;
  5.     vector<int> topological_sort;
  6.     int visited_nodes = 0;
  7.    
  8.     vector<int> indegree = getIndegree(graph);
  9.    
  10.     for (int i = 0; i < graph.size(); i++)
  11.     {
  12.         tuple<int,int,int> tuple = graph[i][0];
  13.        
  14.         if(indegree[i] == 0)
  15.             Z.push(get<0>(tuple) - 1);
  16.     }
  17.    
  18.     while (!Z.empty())
  19.     {        
  20.         int vertex = Z.front();
  21.         //cout << vertex;
  22.         Z.pop();
  23.         topological_sort.push_back(vertex);
  24.  
  25.         for (int i = 1; i < graph[vertex].size(); i++)
  26.         {
  27.             tuple<int,int,int> tuple = graph[vertex][i];
  28.             int idx = get<0>(tuple) - 1;
  29.  
  30.             indegree[idx] -= 1;
  31.  
  32.             if(indegree[idx] == 0)
  33.             {
  34.                 Z.push(idx);
  35.             }
  36.         }
  37.  
  38.         visited_nodes++;  
  39.     }
  40.  
  41.     if(visited_nodes !=  graph.size())
  42.     {
  43.         cout << "There is a cycle!" << endl;
  44.         //return vector<int>(0);
  45.     }
  46.  
  47.     return topological_sort;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement