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.

猜你喜欢

转载自blog.csdn.net/weixin_43748092/article/details/85221414
one