zoukankan      html  css  js  c++  java
  • Coursera Algorithms week1 查并集 练习测验:2 Union-find with specific canonical element

    题目原文:

    Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union(), connected(), and find() should all take logarithmic time or better. 

     1 import edu.princeton.cs.algs4.StdIn;
     2 import edu.princeton.cs.algs4.StdOut;
     3 
     4 public class FindLargestUF {
     5     private int[] id;
     6     private int count;
     7     public FindLargestUF(int n) {
     8         count = n;
     9         id = new int[n];
    10         for (int i = 0; i < n; i++)
    11             id[i] = i;
    12     }
    13     public int count(){
    14         return count;
    15     }
    16     public boolean connected(int p, int q){
    17         return (find(p)==find(q));
    18     }
    19     public int find(int p) {
    20         while (p != id[p])
    21             p = id[p];
    22         return p;
    23     }
    24 
    25     public void union(int p, int q) {
    26         int pRoot = find(p);
    27         int qRoot = find(q);
    28         StdOut.println("find("+p+")="+pRoot+",find("+q+")="+qRoot);
    29         if (pRoot == qRoot)
    30             return;
    31         else if (pRoot < qRoot)
    32             id[pRoot] = qRoot;
    33         else
    34             id[qRoot] = pRoot;
    35         count--;
    36     }
    37 
    38     public static void main(String[] args) {
    39         int n = StdIn.readInt();
    40         FindLargestUF uf = new FindLargestUF(n);
    41         while (!StdIn.isEmpty()) {
    42             int p = StdIn.readInt();
    43             int q = StdIn.readInt();
    44             if (uf.connected(p, q))
    45                 continue;
    46             uf.union(p, q);
    47             StdOut.println("link points:" + p + " " + q);
    48         }
    49         StdOut.println(uf.count() + "components");
    50     }
    51 }

    For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components.

    分析:

    这一题很简单,要求find到的根是子集中的最大元素。因此只需要在union时,用两个子集中较大的root作为合并后的root就可以了。以下代码提交100

  • 相关阅读:
    Android SDK、NDK、JNI的简单介绍
    深入理解计算机系统—异常
    Jmeter3.1 使用及新增报告功能
    jmeter3.1连接数据库报错,ORA00923: 未找到要求的 FROM 关键字
    Jenkins插件、war下载地址
    jenkins自动打tag
    jenkins参数化构建过程
    Jmeter接口测试自动化(jmeter+ant+jenkins持续集成)
    既然选择开始就不会停下
    知识提升整体
  • 原文地址:https://www.cnblogs.com/evasean/p/7204540.html
Copyright © 2011-2022 走看看