Advertisement
nikunjsoni

685

Apr 27th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> parent;
  4. public:
  5.     int findParent(int x){
  6.         return (parent[x] == x) ? x: (parent[x] = findParent(parent[x]));
  7.     }
  8.    
  9.     vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
  10.         int n = edges.size();
  11.         parent.resize(n+1, 0);
  12.         vector<int> p1, p2;
  13.        
  14.         /// There are 2 possibilities of flaw edge:
  15.         // 1. One which makes a node have 2 parents.
  16.         // 2. One which forms a cycle in tree.
  17.        
  18.         for(auto &edge: edges){
  19.             if(parent[edge[1]] == 0)
  20.                 parent[edge[1]] = edge[0];
  21.             else{
  22.                 p1 = {parent[edge[1]], edge[1]};
  23.                 p2 = edge;
  24.                 edge[1] = 0; // Virtually remove edge making a node have 2 parents.
  25.             }
  26.         }
  27.        
  28.         for(int i=1; i<=n; i++)
  29.             parent[i] = i;
  30.        
  31.         // Now each node has only 1 parent. So the possibility of 2 parents is gone.
  32.         // If a cycle is found now, return p1 if it exists, else return the edge forming cycle.
  33.         for(auto edge: edges){
  34.             if(edge[1] == 0) continue;
  35.             int x = edge[0]; int y = edge[1];
  36.             int px  = findParent(edge[0]);
  37.             if(px == y){
  38.                 if(p1.size()) return p1;
  39.                 return edge;
  40.             }
  41.             parent[y] = px;
  42.         }
  43.         // If things go fine, our assumption of removing earlier edge was right, so return that edge.
  44.         return p2;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement