Advertisement
farkhatmikhalko

redundant-connection

Nov 14th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. /*
  2. Runtime: 4 ms, faster than 98.67% of C++ online submissions for Redundant Connection.
  3. Memory Usage: 10.3 MB, less than 47.06% of C++ online submissions for Redundant Connection.
  4. */
  5.  
  6. class Solution {
  7.   const static int SIZE = 1001;
  8.   vector<int> gp[SIZE];
  9.   bool usd[SIZE] = {};
  10.   int qq[SIZE] = {};
  11.   int first = 0;
  12.   bool use = true;
  13. public:
  14.     bool dfs(int v, int p=-1) {
  15.       if(usd[v]) {
  16.         first = v;
  17.         return false;
  18.       }
  19.       usd[v] = true;
  20.       bool ok = true;
  21.       for(auto &e : gp[v]) {
  22.         if(e == p) {
  23.           continue;
  24.         }
  25.         if(ok) {
  26.           ok &= dfs(e, v);
  27.         }
  28.       }
  29.       if(!ok && use) {
  30.         qq[v] = 1;
  31.         use = v!=first;
  32.       }
  33.       return ok;
  34.     }
  35.     vector<int> findRedundantConnection(vector<vector<int>>& edges) {
  36.       int x = 0, len = edges.size();
  37.       for(int i = 0; i < len; i++) {
  38.         int a = edges[i][0];
  39.         int b = edges[i][1];
  40.         gp[a].push_back(b);
  41.         gp[b].push_back(a);
  42.         x = b;
  43.       }
  44.       dfs(x);
  45.       for(int i = 0; i < len; i++) {
  46.         if(qq[edges[len-i-1][0]]+qq[edges[len-i-1][1]] == 2) {
  47.           return edges[len-i-1];
  48.         }
  49.       }
  50.       return edges[0];
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement