不相交集python实现

1.不相交集是解决等价关系的一种数据结构,执行合并和查找的速度都非常快,M次运行合并和查找的运行时间为(M*logN)。

在一个集合中,对于每一对元素(a,b),a,b∈S,对于关系R如果满足下面三个条件,则成关系R为等价关系:

(1)自反性  对于所有a∈S,aRa

(2)对称性   aRb当且仅当bRa

(3)传递性   若aRb且bRc,则aRc

有关不相交集的介绍和C语言实现,点此查看

本文介绍的是不相交集的find和union操作的python实现:

def init(a):
	for i in range(0,110):
		a.append(-1);
def unionset(root1,root2):              #按照大小求并
	tmp=a[root1]+a[root2];
	if a[root1]<=a[root2]:
		a[root2]=root1;	
		a[root1]=tmp;
	else :
		a[root1]=root2;
		a[root2]=tmp;
		
def unions(root1,root2):                #按照高度求并
	if a[root1]>a[root2]:
		a[root1]=root2;
	else:
		if a[root1] is a[root2]:   #只有在高度相同的时候才进行合并
			a[root1]=a[root1]-1;
		a[root2]=root1;
		
def find(a,x):
	if a[x]<=-1:
		return x;
	else :
		return find(a,a[x]);
		

a=[];            #测试代码
init(a);
unionset(1,2);   #按大小求并
unionset(3,4);
unions(5,6);     # 按高度求并
unions(5,7);
print find(a,2);
unionset(1,3);
print find(a,4);
print find(a,5);
print find(a,7);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值