并查集的查找,归并操作

一般二叉树的结构是:数据域+左右孩子,指针域是指向孩子的,称为树的孩子表示法;
但归并集往往是判断元素是否在同一个集合,因此构造的结构是:数据域+指针域,其中指针指向父节点,称为树的双亲表示法。

并查集常常用来实现连接关系的传递性,例如A连接B,B连接C,那么并查集就可以实现A,B,C全部连接。

原题PTA
We have a network of computers and a list of bi-directional connections. Each of these connections allows a file transfer from one computer to another. Is it possible to send a file from any computer on the network to any other?

Input Specification:
Each input file contains one test case. For each test case, the first line contains N (2≤N≤10^4), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:
I c1 c2
where I stands for inputting a connection between c1 and c2; or
C c1 c2
where C stands for checking if it is possible to transfer files between c1 and c2; or
S
where S stands for stopping this case.

Output Specification:
For each C case, print in one line the word “yes” or “no” if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line “The network is connected.” if there is a path between any pair of computers; or “There are k components.” where k is the number of connected components in this network.

Sample Input 1:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
S

Sample Output 1:
no
no
yes
There are 2 components.

Sample Input 2:
5
C 3 2
I 3 2
C 1 5
I 4 5
I 2 4
C 3 5
I 1 3
C 1 5
S

Sample Output 2:
no
no
yes
yes
The network is connected.

一种实现并查集的方式是结构数组:
数据域+指针域(指向父亲)
这样查找某个元素的时候直接遍历结构数组,搜索节点时间复杂度是O(n);在由节点不断向上找父亲,时间复杂度logn;如果查找n次时间复杂度就是O(n^2),PTA上后面几个测试过不了。

一种改进方法是:
本题输入很特殊,数据范围1~N,正好可以对应数组
0~N-1下标,这样使得搜索节点的时间为O(1),找父亲时间为logn,总体时间复杂度似乎为nlogn。代码如下:

def merge(L,seq):
	
	parent1=seq[0]-1
	while L[parent1]>-1:
		parent1=L[parent1]
	parent2=seq[1]-1
	while L[parent2]>-1:
		parent2=L[parent2]
	#if parent1==-1 and parent2==-1:

	if parent1!=parent2:
		L[parent2]=parent1
	#print(L)
	
def isconnect(L,seq):
	parent1=seq[0]-1
	while L[parent1]>-1:
		parent1=L[parent1]
	parent2=seq[1]-1
	while L[parent2]>-1:
		parent2=L[parent2]
	return parent1==parent2

def countconnect(L):
	n=0
	for e in L:
		if e==-1:
			n+=1
	return n


N=int(input())
L=[-1 for i in range(N)]
while True:
	commond=input().split()
	seq=list(map(int,commond[1:]))
	if commond[0]=='I':
		merge(L,seq)
	elif commond[0]=='C':
		if isconnect(L,seq):
			print('yes')
		else:
			print('no')
	elif commond[0]=='S':
		break

if countconnect(L)==1:
	print('The network is connected.')
else:
	print('There are '+str(countconnect(L))+' components.')

但是发现后面几个测试仍然过不了

原因是因为当树往一边偏的时候找节点时间复杂度退化为n。
因此,需要在merg选择父节点的时候改进,尽量使得树的高度接近logn。

按秩归并

按树高归并,矮树归并到高树

def merge(L,seq):
	
	parent1=seq[0]-1
	while L[parent1]>-1:
		parent1=L[parent1]
	parent2=seq[1]-1
	while L[parent2]>-1:
		parent2=L[parent2]
	#if parent1==-1 and parent2==-1:

	if parent1!=parent2:
		#树1高度更大
		if L[parent1]<L[parent2]:
			L[parent2]=parent1
		#树2高度更大
		elif L[parent1]>L[parent2]:
			L[parent1]=parent2
		#相同高度
		else:
			L[parent2]=parent1
			L[parent1]=L[parent1]-1
	#print(L)
def isconnect(L,seq):
	parent1=seq[0]-1
	while L[parent1]>-1:
		parent1=L[parent1]
	parent2=seq[1]-1
	while L[parent2]>-1:
		parent2=L[parent2]
	return parent1==parent2

def countconnect(L):
	n=0
	for e in L:
		if e<0:
			n+=1
	return n


N=int(input())
L=[-1 for i in range(N)]
while True:
	commond=input().split()
	seq=list(map(int,commond[1:]))
	if commond[0]=='I':
		merge(L,seq)
	elif commond[0]=='C':
		if isconnect(L,seq):
			print('yes')
		else:
			print('no')
	elif commond[0]=='S':
		break

if countconnect(L)==1:
	print('The network is connected.')
else:
	print('There are '+str(countconnect(L))+' components.')

按树的规模归并,小树归并到大树

def merge(L,seq):
	
	parent1=seq[0]-1
	while L[parent1]>-1:
		parent1=L[parent1]
	parent2=seq[1]-1
	while L[parent2]>-1:
		parent2=L[parent2]
	#if parent1==-1 and parent2==-1:

	if parent1!=parent2:
		#树1规模更大
		if L[parent1]<L[parent2]:
			L[parent1]=L[parent1]+L[parent2]
			L[parent2]=parent1

		#树2规模更大
		elif L[parent1]>=L[parent2]:
			L[parent2]=L[parent1]+L[parent2]
			L[parent1]=parent2

上面通过尽量平衡树高改善了搜索节点的时间,但是可以压缩路径进一步缩短时间。
压缩路径:前面的代码搜索树的父亲需要logn,但按理说一个节点属于某个集合只是一个归属关系,只需要两层树就可以实现。于是从这个出发,每次在查找的时候都顺带着把查找路径上的节点的归属关系改为只有一层。(有点类似原来需要层层向领导汇报,现在直接和boss面对面,方便了以后的搜索)
改进代码如下:
这里使用尾递归编译器会自动优化为循环,所以不用担心空间复杂度问题。

def findparent(L,elem):
	if L[elem]<0:
		return elem
	L[elem]=findparent(L,L[elem])
	return L[elem]

def merge(L,seq):
	
	parent1=findparent(L,seq[0]-1)
	parent2=findparent(L,seq[1]-1)

	if parent1!=parent2:
		#树1规模更大
		if L[parent1]<L[parent2]:
			L[parent1]=L[parent1]+L[parent2]
			L[parent2]=parent1

		#树2规模更大
		elif L[parent1]>=L[parent2]:
			L[parent2]=L[parent1]+L[parent2]
			L[parent1]=parent2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值