@(132 - ACM | 算法)

Algorithm | Coursera - by Robert Sedgewick

> Tip: Focus on WHAT is really important!
> Don't just copy it!
> Don't look at the subtitle
> Practice is the key. Just Do it!

Backup

P.S. iff == if and only if

0 Introduction

  • Dynamic connectivity problem
  • union-find data type
  • quick find
  • quick union
  • improvements
    • weighted quick union
    • weighted quick union with path compression
  • applications
    • Maze Problem

1 Steps to developing a usable algorithm

  • Model the problem
  • Find a algorithm
  • Fast enough? Fits in memory?
  • if not, figure out why
  • Find a way to address the problem
  • Iterate until satisfied

2 Quick Find | 快速查找

Structure - Linear

Java implementation

public class QuickFindUF
{
private int[] id; //constructor
public QuickFindUF(int N)
{
id = new int[N];//allocate N*int
for (int i = 0;i<N;i++)
id[i] = i;
} public boolean connected(int p,int q)
{
return id[p] == id[q];
} public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0;i<id.length;i++)
{
if(id[i]==pid) id[i] = qid;
}
}
}

Quick find is too slow

3 Quick Union

Structure-Tree

  • Check if they have the same root

    inspire: use the third standard as Reference//第三方标准作为参照物,语言同理

Java implementation

public class QuickUnionUF
{
private int[] id;
//constructor —— set each element to be its own root
public QuickUnionUF(int N)
{
id = new int[N];
for (int i = 0;i < N;i++) id[i] = i;
}
//find the root by chasing parent pointers
private int root(int i)
{
while (i != id[i] i = id[i]);
return i;
} public boolean connected(int p, int q)
{
return root(p) == root(q);
}
public void union(int p,int q)
{
int i = root(p);
int j = root(q);
id[i] = j;
}
}

Quick Union is also too slow

4 Quik-Union Improvement1 -Weighted quick-union

smaller tree down below - small depends on the bigger( size)

demo

improvement

Java implementation

//Data Structure
//maintain extra array sz[i] to count number of objects in the tree rooted at i
//sz[i] = size of tree rooted i // Find - identical to quick-union //Union
//Modify quick-union to:
//1.Link root of smaller tree to root of larger tree.
//2.Update the sz[] array
int i = root(p);
int j = root(q);
if (i == j) return;
if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]};
else { id[j] = i; sz[i] += sz[j]};

Runing time

O(N) = lg N


5 Quik-Union Improvement2 -Path compression

Flatten the tree

In practice - Keeps tree almost completely flat.


java implementation

  • Make every other node in path point to its grandparent

private int root(int i)
{
while(i != id[i])
{
id[i] = id[id[i]];//only one extra line of code!
i = id[i];
}
return i;
}

O(N) = N+M * lgN

6 Summary for solving the dynamic connectivity problem

7 Union-Find Application

Percolation

Monte Carlo simulation //蒙特卡罗模拟

Dynamic connectivity solution to estimate percolation threshold

  • Clever Trick

8 Application - Percolation | 渗滤问题

需要注意的是Timing和Backwash的问题

  • Timing:PercolationStats.java里StdRandom.mean()和StdRandom.stddev()都只能调用一次;Percolation.java里实现numberOfOpenSites时切记不能使用循环累加,定义一个私有属性来计数即可;实现open()时相邻的四个sites位置直接加减n或1即可。

  • Backwash:实现isFull()时需要另外实例化一个不包含最下端虚拟节点的WeightedQuickUnionUF,可以解决Test 13: check for backwash with predetermined sites,Test 14: check for backwash with predetermined sites that have multiple percolating paths和Test 15: call all methods in random order until all sites are open, allowing isOpen() to be called on a site more than once

三项测试无法通过的问题。Backwash问题是指因为虚拟底部结点的存在,导致底部任一结点渗漏成功的话底部所有结点都会认为渗漏成功。原因是通过底部虚拟结点形成了回流。从而导致isFull()方法出错。

参考链接

  • Percolation.java
import edu.princeton.cs.algs4.WeightedQuickUnionUF;

public class Percolation {

	private boolean[] op; // true=open while false=blocked
private int side; // number of rows or columns
private int numOp; // number of open sites
private WeightedQuickUnionUF uf;
private WeightedQuickUnionUF ufTop; public Percolation(int n) { if(n <= 0) throw new IllegalArgumentException("Input should be positif!\n"); this.side = n;
this.op = new boolean[n*n+2]; // with 2 virtual sites
this.uf = new WeightedQuickUnionUF(n*n+2);
this.ufTop = new WeightedQuickUnionUF(n*n+1); // with only the upper virtual site for(int i=1; i<n*n+1; i++) op[i] = false;
op[0] = op[n*n+1] = true;
this.numOp = 0; } // both ROW and COL should be integer within 1~n
private void checkBounds(int row, int col){
if(row < 1 || row > this.side || col < 1 || col > this.side){
throw new IllegalArgumentException("Index out of bounds!\n");
}
} // get position of sites in 3 arrays: op, uf.parent & uf.size
private int getPosition(int row, int col){
return (row - 1) * this.side + col;
} private void union(int aPos, int bPos, WeightedQuickUnionUF wq){
if(!wq.connected(aPos, bPos)){
wq.union(aPos, bPos);
}
} private boolean isOpen(int pos){
return op[pos];
} public void open(int row, int col) { checkBounds(row, col);
if(isOpen(row, col)) return; int pos = getPosition(row, col);
op[pos] = true;
numOp++; // positions of adjacent sites
int rowPrev = pos - side, rowNext = pos + side,
colPrev = pos - 1, colNext = pos + 1; // try connect the adjacent open sites
if(row == 1){
union(0, pos, uf);
union(0, pos, ufTop);
}else if(isOpen(rowPrev)){
union(rowPrev, pos, uf);
union(rowPrev, pos, ufTop);
} if(row == side){
union(side * side + 1, pos, uf);
}else if(isOpen(rowNext)){
union(rowNext, pos, uf);
union(rowNext, pos, ufTop);
} if(col != 1 && isOpen(colPrev)) {
union(colPrev, pos, uf);
union(colPrev, pos, ufTop);
} if(col != side && isOpen(colNext)) {
union(colNext, pos, uf);
union(colNext, pos, ufTop);
}
} public boolean isOpen(int row, int col) {
checkBounds(row, col);
return isOpen(getPosition(row, col)); } /**
* check for backwash with predetermined sites that have multiple percolating paths
* in this case ufTop should be used instead of uf
* @param row
* @param col
* @return
*/
public boolean isFull(int row, int col) {
checkBounds(row, col);
//return uf.connected(0, getPosition(row, col)); -> didn't pass the test!
return ufTop.connected(0, getPosition(row, col)); } // should pass the timing check
public int numberOfOpenSites(){
return this.numOp;
} public boolean percolates(){
return uf.connected(0, side * side + 1);
} }
  • PercolationStats.java

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;
import edu.princeton.cs.algs4.Stopwatch; public class PercolationStats { private double[] results; // estimated threshold for each trial
private double avg;
private double std; public PercolationStats(int n, int trials){ if(n <= 0 || trials <= 0) throw new IllegalArgumentException(); results = new double[trials];
for(int i = 0; i < trials; i++){
int step = 0;
Percolation pr = new Percolation(n);
while(!pr.percolates()){
int row = StdRandom.uniform(n) + 1;
int col = StdRandom.uniform(n) + 1;
if(!pr.isOpen(row, col)){
pr.open(row, col);
step++;
}
}
results[i] = (double)step / (n * n);
} this.avg = StdStats.mean(results);
this.std = StdStats.stddev(results); } public static void main(String[] args){ StdOut.printf("%-25s\n", "Please input 2 integers");
int N = StdIn.readInt();
int T = StdIn.readInt(); Stopwatch wt = new Stopwatch(); PercolationStats ps = new PercolationStats(N, T); // elapsed CPU time in seconds
double elapsed = wt.elapsedTime(); StdOut.printf("%-25s= %.15f\n", "elapsed CPU time", elapsed);
StdOut.printf("%-25s= %.7f\n", "mean", ps.mean());
StdOut.printf("%-25s= %.17f\n", "stddev", ps.stddev());
StdOut.printf("%-25s= [%.15f, %.15f]\n", "%95 confidence interval",
ps.confidenceLo(), ps.confidenceHi());
} public double mean(){
return this.avg;
} public double stddev(){
return this.std;
} public double confidenceLo(){
return mean() - 1.96 * stddev() / Math.sqrt(results.length);
} public double confidenceHi(){
return mean() + 1.96 * stddev() / Math.sqrt(results.length);
} }

132.1.001 Union-Find | 并查集的更多相关文章

  1. <算法><Union Find并查集>

    Intro 想象这样的应用场景:给定一些点,随着程序输入,不断地添加点之间的连通关系(边),整个图的连通关系也在变化.这时候我们如何维护整个图的连通性(即判断任意两个点之间的连通性)呢? 一个比较简单 ...

  2. 并查集(Union/Find)模板及详解

    概念: 并查集是一种非常精巧而实用的数据结构,它主要用于处理一些不相交集合的合并问题.一些常见的用途有求连通子图.求最小生成树的Kruskal 算法和求最近公共祖先等. 操作: 并查集的基本操作有两个 ...

  3. 并查集(Union Find)的基本实现

    概念 并查集是一种树形的数据结构,用来处理一些不交集的合并及查询问题.主要有两个操作: find:确定元素属于哪一个子集. union:将两个子集合并成同一个集合. 所以并查集能够解决网络中节点的连通 ...

  4. 并查集 (Union Find ) P - The Suspects

    Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized ...

  5. 并查集(Disjoint Set Union,DSU)

    定义: 并查集是一种用来管理元素分组情况的数据结构. 作用: 查询元素a和元素b是否属于同一组 合并元素a和元素b所在的组 优化方法: 1.路径压缩 2.添加高度属性 拓展延伸: 分组并查集 带权并查 ...

  6. 第三十一篇 玩转数据结构——并查集(Union Find)

    1.. 并查集的应用场景 查看"网络"中节点的连接状态,这里的网络是广义上的网络 数学中的集合类的实现   2.. 并查集所支持的操作 对于一组数据,并查集主要支持两种操作:合并两 ...

  7. 并查集(不相交集)的Union操作

    在并查集(不相交集)中附加操作\(Deunion\),它实现的功能是取消最后一次\(Union\)的操作. 实现思想 初始化一个空栈,将每一次的\(Union\)操作的两个集合的根和其值\(Push\ ...

  8. Mutual Training for Wannafly Union #6 E - Summer Trip(并查集)

    题目链接:http://www.spoj.com/problems/IAPCR2F/en/ 题目大意: 给m个数字代表的大小,之后n组数据,两两关联,关联后的所有数字为一组,从小到大输出组数以及对应的 ...

  9. POJ 1611 The Suspects 并查集 Union Find

    本题也是个标准的并查集题解. 操作完并查集之后,就是要找和0节点在同一个集合的元素有多少. 注意这个操作,须要先找到0的父母节点.然后查找有多少个节点的额父母节点和0的父母节点同样. 这个时候须要对每 ...

  10. BZOJ 1050 旅行comf(枚举最小边-并查集)

    题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=1050 题意:给出一个带权图.求一条s到t的路径使得这条路径上最大最小边的比值最小? 思路 ...

随机推荐

  1. Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理

    token处理之二使用JWT替换默认的token JWT(Json Web Token) 特点: 1,自包含:jwt token包含有意义的信息 spring security oauth默认生成的t ...

  2. java文件上传-原始的Servlet方式

    前言: 干了这几个项目,也做过几次文件上传下载,要么是copy项目以前的代码,要么是百度的,虽然做出来了,但学习一下原理弄透彻还是很有必要的.刚出去转了一圈看周围有没有租房的,在北京出去找房子是心里感 ...

  3. centos6 和 centos7 网络配置

    centos 6配置,1 vim /etc/sysconfig/network-scripts/ifcfg-eth0DEVICE="eth0" BOOTPROTO="st ...

  4. win7安装docker报错:error during connect: Get http ..... the system cannot find the file specified

    因为是win7 所以使用了官方网站的dockertoolbox 安装一路顺利,结果启动就报上面的错误, 因为安装包附带安装了virtualbox 上面的错误后来排查出来是 virtualboox的问题 ...

  5. Android 开发服务类 04_ServletForPOSTMethod

    ServletForPOSTMethod 业务类 package com.wangjialin.internet.servlet; import java.io.IOException; import ...

  6. HUE配置文件hue.ini 的hbase模块详解(图文详解)(分HA集群和非HA集群)

    不多说,直接上干货! 我的集群机器情况是 bigdatamaster(192.168.80.10).bigdataslave1(192.168.80.11)和bigdataslave2(192.168 ...

  7. 机器学习--集成学习(Ensemble Learning)

    一.集成学习法 在机器学习的有监督学习算法中,我们的目标是学习出一个稳定的且在各个方面表现都较好的模型,但实际情况往往不这么理想,有时我们只能得到多个有偏好的模型(弱监督模型,在某些方面表现的比较好) ...

  8. centos6 内网可达,外网不可达 Network is unreachable

    错误内容 [root@djx-2 yum.repos.d]# ping 3.0.82.21 connect: Network is unreachable [root@djx-2 yum.repos. ...

  9. HTML引入CSS样式的四种方法

    在HTML中引入CSS的方法主要有四种,它们分别是行内式.内嵌式.链接式和导入式. 1.行内式          行内式是在标记的style属性中设定CSS样式.这种方式没有体现出CSS的优势,不推荐 ...

  10. MVC、MVCS、MVVM、MVP、VIPER等这么多架构模式哪一个好呢?

    在项目开启阶段,其中一个很重要的环节就是选架构. 那么面对目前已知的这么多架构模式我们该怎么选择呢?这确实是个很让人头疼的问题!   下面我就在这里梳理一下目前常见的一些架构模式. 先逐个对它们的分析 ...