博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 685. Redundant Connection II 冗余的连接之 II
阅读量:4630 次
发布时间:2019-06-09

本文共 5488 字,大约阅读时间需要 18 分钟。

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   v2-->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:

  • The size of the input 2D-array will be between 3 and 1000.
  • Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.

 的拓展,684题给的是无向图,只需要删掉组成环的最后一条边即可,检测环就行了。这题给的是有向图,就复杂多了,有多种情况存在,比如例子1就是无环,但是有入度为2的结点3。再比如例子2是有环,但是没有入度为2的结点。还有一种情况例子没有给出,就是既有环,又有入度为2的结点。

解法:Union find

There are two cases for the tree structure to be invalid.

1) A node having two parents;
including corner case: e.g. [[4,2],[1,5],[5,2],[5,3],[2,4]]
2) A circle exists

If we can remove exactly 1 edge to achieve the tree structure, a single node can have at most two parents. 

1) Check whether there is a node having two parents.

If so, store them as candidates A and B, and set the second edge invalid.
2) Perform normal union find.

If the tree is now valid

    simply return candidate B
else if candidates not existing
    we find a circle, return current edge;
else
    remove candidate A instead of B.

Java:

class Solution {    public int[] findRedundantDirectedConnection(int[][] edges) {        int[] can1 = {-1, -1};        int[] can2 = {-1, -1};        int[] parent = new int[edges.length + 1];        for (int i = 0; i < edges.length; i++) {            if (parent[edges[i][1]] == 0) {                parent[edges[i][1]] = edges[i][0];            } else {                can2 = new int[] {edges[i][0], edges[i][1]};                can1 = new int[] {parent[edges[i][1]], edges[i][1]};                edges[i][1] = 0;            }        }        for (int i = 0; i < edges.length; i++) {            parent[i] = i;        }        for (int i = 0; i < edges.length; i++) {            if (edges[i][1] == 0) {                continue;            }            int child = edges[i][1], father = edges[i][0];            if (root(parent, father) == child) {                if (can1[0] == -1) {                    return edges[i];                }                return can1;            }            parent[child] = father;        }        return can2;    }        int root(int[] parent, int i) {        while (i != parent[i]) {            parent[i] = parent[parent[i]];            i = parent[i];        }           return i;    }}

Python:

# Time:  O(nlog*n) ~= O(n), n is the length of the positions# Space: O(n)class UnionFind(object):    def __init__(self, n):        self.set = range(n)        self.count = n    def find_set(self, x):        if self.set[x] != x:            self.set[x] = self.find_set(self.set[x])  # path compression.        return self.set[x]    def union_set(self, x, y):        x_root, y_root = map(self.find_set, (x, y))        if x_root == y_root or \           y != y_root:  # already has a father            return False        self.set[y_root] = x_root        self.count -= 1        return Trueclass Solution(object):    def findRedundantDirectedConnection(self, edges):        """        :type edges: List[List[int]]        :rtype: List[int]        """        union_find = UnionFind(len(edges)+1)        for edge in edges:            if not union_find.union_set(*edge):                return edge        return []  

C++:

class Solution {public:    vector
findRedundantDirectedConnection(vector
>& edges) { int n = edges.size(); vector
parent(n+1, 0), candA, candB; // step 1, check whether there is a node with two parents for (auto &edge:edges) { if (parent[edge[1]] == 0) parent[edge[1]] = edge[0]; else { candA = {parent[edge[1]], edge[1]}; candB = edge; edge[1] = 0; } } // step 2, union find for (int i = 1; i <= n; i++) parent[i] = i; for (auto &edge:edges) { if (edge[1] == 0) continue; int u = edge[0], v = edge[1], pu = root(parent, u); // Now every node only has 1 parent, so root of v is implicitly v if (pu == v) { if (candA.empty()) return edge; return candA; } parent[v] = pu; } return candB; }private: int root(vector
& parent, int k) { if (parent[k] != k) parent[k] = root(parent, parent[k]); return parent[k]; }};

 

 

类似题目:

 

 

转载于:https://www.cnblogs.com/lightwindy/p/9795726.html

你可能感兴趣的文章
html 11 内联(行内)
查看>>
NOIP模拟题 斐波那契数列
查看>>
增删改查
查看>>
【bzoj3261】最大异或和 可持久化Trie树
查看>>
西门子smart200以太网通讯协议
查看>>
ActiveMQ消息存储持久化
查看>>
JAVA SHA1 加密 对应 c# SHA1 加密
查看>>
创建一个没有边框的并添加自定义文字的UISegmentedControl
查看>>
IOS沙盒Files目录说明和常用操作
查看>>
linxu passwd 给linux用户设置密码 命令
查看>>
mongodb的shell命令
查看>>
Windows Phone开发(7):当好总舵主 转:http://blog.csdn.net/tcjiaan/article/details/7281421...
查看>>
Android UI体验之全屏沉浸式透明状态栏效果
查看>>
STM32普通定时器(TIM2-7)的时钟源
查看>>
使用机智云APP控制战舰V3 (转)
查看>>
单相计量芯片RN8209D使用经验分享(转)
查看>>
SD卡的控制方法(指令集和控制时序)
查看>>
zabbix4.0构建实录
查看>>
javascript保留字
查看>>
assert
查看>>