1. 程式人生 > >Princeton大學教授演算法課程weekone one

Princeton大學教授演算法課程weekone one

Quick-Union,lazy-approch.

Data Structure
1、Integer array id[] of size n
2、Interpretation:id[i] is parent of i
3、Root of i is id[id[id[i]]]… until it can’t change

we think about the arrray as a forest with a lot of trees.(take care)
在這裡插入圖片描述
as you can see from this picture ,9 is the father and 2、4、3 are its sons.
use this data structure we can find these connected components.

Find check if p and q have the same root.
Union to merge components containing p and q,set the id of p’s root to the id of q’s root.

now,we should see this process.
now id[4]=3now id[4]=3
在這裡插入圖片描述now id[3]=8.
as the array shows
在這裡插入圖片描述在這裡插入圖片描述as the array shows
在這裡插入圖片描述

package weekone;

public class QuickUnionUF {
	private  int [] id;
	public  QuickUnionUF(int n)
	{
		id = new int[n];
		for(int i=0;i<n;i++)
		{
			id[i]=i;
		}
	}
	
	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;
	}
	
	public static void main(String[] args) {
		QuickUnionUF s =new QuickUnionUF(10);
		s.union(4,3);
		s.union(3,8);
		s.union(9,8);
		System.out.println(s.connected(4,9));
	}
	
}

and the result is true.