前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 51:684. Redundant Connection

LWC 51:684. Redundant Connection

作者头像
用户1147447
发布2018-01-02 11:06:31
5190
发布2018-01-02 11:06:31
举报
文章被收录于专栏:机器学习入门机器学习入门

LWC 51:684. Redundant Connection

传送门:684. Redundant Connection

Problem:

We are given a “tree” in the form of a 2D-array, with distinct values for each node. In the given 2D-array, each element pair [u, v] represents that v is a child of u in the tree. We can remove exactly one redundant pair in this “tree” to make the result a tree. You need to find and output such a pair. If there are multiple answers for this question, output the one appearing last in the 2D-array. There is always at least one answer.

Example 1:

Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: Original tree will be like this: 1 / \ 2 - 3

Example 2:

Input: [[1,2], [1,3], [3,1]] Output: [3,1] Explanation: Original tree will be like this: 1 / \\ 2 3

Note:

The size of the input 2D-array will be between 1 and 1000.

Every integer represented in the 2D-array will be between 1 and 2000.

思路: 检测是否有冗余的边,意味着一条新的边加入之后,原先的连通性没有发生变化,用并查集即可。判断加入新边时,判断这两个结点在原先的结构中是否被连通,如果连通只能说明此边是冗余的,题目保证只有一条这样的边,所以遇到就能输出。

代码如下:

    class Union{
        int[] id;
        int[] sz;

        Union(int n){
            id = new int[n];
            sz = new int[n];
            for (int i = 0; i < n; ++i) {
                id[i] = i;
            }
            Arrays.fill(sz, 1);
        }

        int find(int i) {
            while (i != id[i]) {
                i = id[i];
            }
            return i;
        }

        boolean same(int i, int j) {
            return find(i) == find(j);
        }

        void union(int i, int j) {
            int p = find(i);
            int q = find(j);
            if (p == q) return;

            if (sz[p] > sz[q]) {
                id[q] = p;
                sz[p] += sz[q];
            }
            else {
                id[p] = q;
                sz[q] += sz[p];
            }
        }
    }

    public int[] findRedundantConnection(int[][] edges) {
        int n = edges.length;
        Union union = new Union(2000 + 16);
        for (int i = 0; i < n; ++i) {
            if (union.same(edges[i][0], edges[i][1])) return new int[] {edges[i][0], edges[i][1]};
            else {
                union.union(edges[i][0], edges[i][1]);
            }
        }
        return new int[] {-1,-1};
    }      
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-09-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 51:684. Redundant Connection
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档