算法笔记——数据结构(并查集)

1.并查集的定义  并查集是一种维护集合的数据结构,并(Union合并),查(find查找),set(集合)。  并查集使用数组来实现:

int father[n];

 其中father[i]表示元素i的父亲结点,而父亲结点本身也是这个集合内的元素。eg:father[1] = 2 表示元素1的父结点是元素2。如果father[i] = i ,则说明元素i是该集合的根结点。

2.并查集的基本操作    (1)初始化    每个元素都是独立的一个集合。

for(int i = 1;i <= n; i++){
          
   
	father[i] = i;
}

 (2)查找    根据一个集合中指存在一个根结点,此处查找就是对给定结点寻找其根结点。

//返回x所在集合的根结点
int findFather(int x){
          
   
	while(x != father[x]){
          
   
		x = father[x];
	}
	return x;
}

递归写法:

int findFather(int x){
          
   
	if(x == father[x]) return x;
	else return findFather(father[x]);
}

特殊情况下查找的优化:   当数据很大且进行多次查找时,可使用优化的写法。即先找到根结点后,将所有的结点的父结点都指向根结点,后面的查找复杂度为O(1)。

int findFather(int x){
          
   
	int a = x;
	while(x == Father(x)){
          
   
		x = Father(x);	
	}
	while(a != Father[a]){
          
   
		int y = Father[a];
		a = Father[a];
		Father[y] = x;
	}
	return x;
}

递归写法:

int findFather(int x){
          
   
	if(x == father[x]) return x;
	else{
          
   
		int y = findFather(father[x]);
		father[x] = y;
		return y;
	}
}

 (3)合并

   合并是指把两个集合合并成一个集合。具体实现:判断两个元素是否在不同集合,是则合并,将一个集合的根结点的父亲指向另一个集合的根结点,

void Union(int a,int b){
          
   
	int a = findFather(a);
	int b = findFather(b);
	if(a != b)
		father[a] = b;	
}

并查集产生的每一个集合都是一棵树。

经验分享 程序员 微信小程序 职场和发展