685. Redundant Connection II
Hard
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of
edges
. Each element of edges
is a pair [u, v]
that represents a directed edge connecting nodes u
and v
, where u
is a parent of child v
.
Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
Example 1:
Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: The given directed graph will be like this: 1 / \ v v 2-->3
Example 2:
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]] Output: [4,1] Explanation: The given directed graph will be like this: 5 <- 1 -> 2 ^ | | v 4 <- 3
Note:
- 3 invalid situations
- case1: 2 parents no circle
- case2: 2 parents with circle
- case3: 1 parent with circle
- 2 main steps
- 1 check whether there exists a node with 2 parents, if yes, store the two edges.
- 2 if no edge yielded from step 1, apply union-find and find the edge creating cycle (same as
- 684); ELSE, apply union-find to ALL edges EXCEPT edges from step 1, then check: if edge 1
- from step 1 creates a cycle, return edge 1; else return edge 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | class Solution { int find(map<int, int>& mp, int i){ while(mp[i]!=i){ i = mp[i]; } return i; } //remove redundant edge for graph with no double parents vector<int> findRedundantConnection(vector<vector<int>>& edges, int skipedge = -1) { map<int, int> mp; int i = -1; for(auto& e:edges){ i++; if(i==skipedge) continue; mp[e[0]] = e[0]; mp[e[1]] = e[1]; } i = -1; for(auto& e:edges){ i++; if(i==skipedge) continue; int x = e[0], y = e[1]; int x0 = find(mp, x); int y0 = find(mp, y); if(x0!=y0){ mp[y0] = x0; }else{ return vector<int>{x, y}; } } return vector<int>(); } public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { vector<int> edges2p;//edges form 2 parents map<int, int> mp;//child, index for(int i=0; i<edges.size(); ++i){ int c = edges[i][1]; if(mp.count(c)==0) mp[c] = i; else{ edges2p.push_back(mp[c]); edges2p.push_back(i); break; } } //case 1: no double parent if(edges2p.empty()){ return findRedundantConnection(edges); }else{ vector<int> r = findRedundantConnection(edges, edges2p[1]); if(!r.empty()) return edges[edges2p[0]]; else return edges[edges2p[1]]; } return vector<int>(); } }; |
No comments:
Post a Comment