Advertisement
Iam_Sandeep

topological sort using kahns algorithm

Jun 1st, 2021
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. // { Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5.  // } Driver Code Ends
  6.  
  7.  
  8.  
  9. class Solution
  10. {
  11.     public:
  12.     //Function to return list containing vertices in Topological order.
  13.     void dfs(int src,bool *v,vector<int> &result,vector<int> adj[]){
  14.         v[src]=true;
  15.         for(auto node:adj[src])
  16.             if (v[node]==false){
  17.                 dfs(node,v,result,adj);
  18.             }
  19.        result.push_back(src);
  20.     }
  21.    
  22.     vector<int> topoSort(int V, vector<int> adj[])
  23.     {
  24.         // code here
  25.         bool v[V]={false};
  26.         vector<int> result;
  27.         for(int i=0;i<V;++i)
  28.                 if (v[i]==false)
  29.                      dfs(i,v,result,adj);
  30.        reverse(result.begin(),result.end());
  31.        return result;
  32.            
  33.     }
  34. };
  35.  
  36. // { Driver Code Starts.
  37.  
  38. /*  Function to check if elements returned by user
  39. *   contains the elements in topological sorted form
  40. *   V: number of vertices
  41. *   *res: array containing elements in topological sorted form
  42. *   adj[]: graph input
  43. */
  44. int check(int V, vector <int> &res, vector<int> adj[]) {
  45.     vector<int> map(V, -1);
  46.     for (int i = 0; i < V; i++) {
  47.         map[res[i]] = i;
  48.     }
  49.     for (int i = 0; i < V; i++) {
  50.         for (int v : adj[i]) {
  51.             if (map[i] > map[v]) return 0;
  52.         }
  53.     }
  54.     return 1;
  55. }
  56.  
  57. int main() {
  58.     int T;
  59.     cin >> T;
  60.     while (T--) {
  61.         int N, E;
  62.         cin >> E >> N;
  63.         int u, v;
  64.  
  65.         vector<int> adj[N];
  66.  
  67.         for (int i = 0; i < E; i++) {
  68.             cin >> u >> v;
  69.             adj[u].push_back(v);
  70.         }
  71.        
  72.         Solution obj;
  73.         vector <int> res = obj.topoSort(N, adj);
  74.  
  75.         cout << check(N, res, adj) << endl;
  76.     }
  77.    
  78.     return 0;
  79. }  // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement