查看“Union find”的源代码
←
Union find
跳到导航
跳到搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看和复制此页面的源代码。
[[Category:刷题]] 并查集:用于处理一些不交集(Disjoint sets)的合并及查询问题。 == 算法 == === 添加 === 新添加一个元素时,它的 parent 是它自己。 === 查询 === 每个集合的代表是集合的根节点。在查询时进行路径压缩。 <syntaxhighlight lang=python> def find_representative(x): if x.parent == x: return x else: x.parent = find_representative(x.parent) return x.parent </syntaxhighlight> === 合并 === {{TODO|union}} == 相关题目 == === [https://leetcode.com/problems/number-of-provinces/ LeetCode 547. Number of Provinces] === Python 解法: <syntaxhighlight lang=python> def findCircleNum(self, isConnected: List[List[int]]) -> int: ''' Union Find solution. Begins by seting the number of provinces to the number of cities, then union each pair of the connected cities. If they belong to different sets before the union, reduce the number of provinces by 1 (unioned two cities into one province). ''' city_num = len(isConnected) representative = [i for i in range(city_num)] def find_repr(c): if representative[c] == c: return c else: representative[c] = find_repr(representative[c]) return representative[c] ret = city_num for i in range(city_num): for j in range(i + 1, city_num): if not isConnected[i][j]: continue if (ri := find_repr(i)) != (rj := find_repr(j)): # Connected cities are in different sets. Union them and # reduce the number of provinces representative[ri] = rj ret -= 1 return ret </syntaxhighlight> == 另见 == * [[wikipedia:Disjoint-set_data_structure]]
返回至
Union find
。
导航菜单
个人工具
登录
名字空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
MediaWiki帮助
工具
链入页面
相关更改
特殊页面
页面信息