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

时间: 2024-07-30 20:26:58

coursera Algorithms week1 练习测验2:Union-find with specific canonical element的相关文章

Coursera Algorithms week1 练习测验3:Successor with delete

题目原文: Given a set of n integers S = {0,1,-,N-1}and a sequence of requests of the following form: Remove x from S Find the successor of x: the smallest y in S such thaty>=x design a data type so that all operations(except construction) take logarithmi

Coursera Algorithms week1 Interview Questions: 3Sum in quadratic time

题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case. You may assume that you can sort the n integers in time proportional to n2 or better. 分析: <算法4>这本书提供的TwoSumFast解法为NlogN,ThreeSumFast解法为N2logN,根据课后练

Coursera Algorithms week1 Interview Questions: Search in a bitonic array

题目要求: An array is bitonic if it is comprised of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of n distinct integer values, determines whether a given integer

Coursera Algorithms week3 归并排序 练习测验1: Merging with smaller auxiliary array

题目原文: Suppose that the subarray a[0] to a[n-1] is sorted and the subarray a[n] to a[2*n-1] is sorted. How can you merge the two subarrays so that a[0] to a[2*n-1] is sorted using an auxiliary array of length n (instead of 2n) 分析: 对两个大小分别为n的有序子数组进行归并,

Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts

题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exactly one nut. By fitting a nut and a bolt toget

Coursera Algorithms week2 栈和队列 练习测验: Stack with max

题目原文: Stack with max. Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum operation. Assume the elements are reals numbers so that you can compare them. 分析: 该题目要求在实现正常stack的push和pop操作外,还

Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space

题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a constant amount of extra space. 1 public void traverse(BST<Key,Value> bst) { 2 traverse(bst.root.left, bst.root); 3 } 4 5 private void traverse(Node curre

Coursera Algorithms week4 基础标签表 练习测验:Check if a binary tree is a BST

题目原文: Given a binary tree where each  ???????? contains a key, determine whether it is a binary search tree. Use extra space proportional to the height of the tree. 分析: 就是递归遍历BST,将每个节点x分别与x.left和x.right比大小. 1 public boolean isBST(BST<Key,Value> bst)

Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)

题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respectively, design an algorithm to find the kth largest key. The order  of growth of the worst case running time of your algorithm should be logn, where n