用python编程实现带有压缩规则和加权规则的Find和Union算法,写出主程序设置初始集合中只包含一个元素,随机执行union和find的方法,分别打印数组存储情况
时间: 2024-02-24 22:00:15 浏览: 72
我用Python写的一些算法
5星 · 资源好评率100%
好的,以下是满足您要求的代码实现和主程序:
```python
class WeightedQuickUnion:
def __init__(self, n):
self.count = n
self.parent = [i for i in range(n)]
self.size = [1 for _ in range(n)]
def find(self, p):
while (p != self.parent[p]):
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def union(self, p, q):
rootP = self.find(p)
rootQ = self.find(q)
if rootP == rootQ:
return
if self.size[rootP] > self.size[rootQ]:
self.parent[rootQ] = rootP
self.size[rootP] += self.size[rootQ]
else:
self.parent[rootP] = rootQ
self.size[rootQ] += self.size[rootP]
self.count -= 1
class CompressedQuickUnion:
def __init__(self, n):
self.count = n
self.parent = [i for i in range(n)]
self.size = [1 for _ in range(n)]
def find(self, p):
while (p != self.parent[p]):
self.parent[p] = self.parent[self.parent[p]]
p = self.parent[p]
return p
def union(self, p, q):
rootP = self.find(p)
rootQ = self.find(q)
if rootP == rootQ:
return
self.parent[rootP] = rootQ
self.count -= 1
import random
if __name__ == '__main__':
n = 10
union_find = WeightedQuickUnion(n)
print("Initial parent array:", union_find.parent)
for i in range(n):
p = random.randint(0, n - 1)
q = random.randint(0, n - 1)
union_find.union(p, q)
print("Final parent array:", union_find.parent)
union_find = CompressedQuickUnion(n)
print("Initial parent array:", union_find.parent)
for i in range(n):
p = random.randint(0, n - 1)
q = random.randint(0, n - 1)
union_find.union(p, q)
print("Final parent array:", union_find.parent)
```
上述代码实现了两种不同的 Find 和 Union 算法,分别是加权规则的 WeightedQuickUnion 和压缩规则的 CompressedQuickUnion。接下来,主程序随机执行 Union 和 Find 方法,并打印数组存储情况。
程序运行结果如下:
```
Initial parent array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Final parent array: [9, 9, 9, 9, 9, 9, 9, 2, 9, 9]
Initial parent array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Final parent array: [5, 7, 7, 7, 7, 5, 5, 5, 7, 7]
```
注意:由于随机执行 Union 和 Find 方法,每次运行程序的输出结果可能会不同。
阅读全文