快来!Python详细解法
2026-07-10 18:23:19
发布于:浙江
2阅读
0回复
0点赞
Python解法:
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.count = n # 初始连通块数量为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:
self.parent[root_x] = root_y # 合并集合
self.count -= 1 # 连通块数量减1
def count_beacon_networks(n, beacons):
# 蜂巢网格的6个相邻方向
directions = [(-1, -1), (-1, 0), (0, -1), (0, 1), (1, 0), (1, 1)]
# 用字典存储激活单元,键为坐标元组,值为唯一ID(0到n-1)
beacon_map = {tuple(beacon): i for i, beacon in enumerate(beacons)}
uf = UnionFind(n)
# 遍历每个激活单元,检查其6个相邻位置
for (x, y), idx in beacon_map.items():
for dx, dy in directions:
nx, ny = x + dx, y + dy
if (nx, ny) in beacon_map:
uf.union(idx, beacon_map[(nx, ny)])
return uf.count
# 读取输入
n = int(input())
beacons = []
for _ in range(n):
x, y = map(int, input().split())
beacons.append((x, y))
# 输出结果
print(count_beacon_networks(n, beacons))
全部评论 1
- 置顶
快来戳赞赞~~~~~
3天前 来自 浙江
1

有帮助,赞一个