gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
写一个并查集实现的代码
- User
写一个并查集实现的代码
- Assistant
以下是一个简单示例的并查集实现代码:
pythonclass UnionFind: def __init__(self, n): self.parent = [i for i in range(n)] self.rank = [0] * n def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, x, y): root_x = self.find(x) root_y = self.find(y) if root_x == root_y: return if self.rank[root_x] < self.rank[root_y]: self.parent[root_x] = root_y elif self.rank[root_x] > self.rank[root_y]: self.parent[root_y] = root_x else: self.parent[root_y] = root_x self.rank[root_x] += 1