重点例题 – 继续学习之前,请先尽力独立解决这道题!
资源
| Resources | |||||
|---|---|---|---|---|---|
| CF EDU | DSU 视频讲解与习题 | ||||
| CSA | 两种优化与图示 | ||||
| PAPS1 | 两种优化,无图示 | ||||
| CPH | 启发式合并与图示 | ||||
| IUSACO | 路径压缩与图示 | ||||
| TC | 图示 | ||||
实现
class DisjointSets:def __init__(self, size: int) -> None:self.parents = [i for i in range(size)]self.sizes = [1 for _ in range(size)]def find(self, x: int) -> int:""":return: the "representative" node in x's component"""if self.parents[x] == x:return xself.parents[x] = self.find(self.parents[x])
由于实现非常简单,在计算连通块时,你可能会更愿意用它代替 DFS。
解法——重点题
如果不用并查集,就必须以邻接表表示图,并使用洪水填充计算连通块。 这种方法需要 时间,速度太慢,因此我们改用并查集。
用上面刚实现的并查集表示图后,既可以用它的方法_合并_顶点,也可以判断两个顶点 和 是否位于同一连通块中,每次操作的均摊时间仅为 。
这样,总时间复杂度降至 ,提升十分显著,足以通过所有测试点。
实现
时间复杂度:
Code Snippet: DSU (Click to expand)size, query_num = [int(i) for i in input().split()]dsu = DisjointSets(size)for _ in range(query_num):q_type, u, v = [int(i) for i in input().split()]if q_type == 0:dsu.unite(u, v)else:print(1 if dsu.connected(u, v) else 0)
题目
标准题
你应该已经熟悉“Wormhole Sort”和“Moocast”的 DFS / 二分查找解法。
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CSES | Easy | Show TagsDSU | ||||
| Gold | Easy | Show TagsDSU | ||||
| Gold | Easy | Show TagsDSU | ||||
| Silver | Easy | Show TagsDSU | ||||
| Gold | Easy | Show TagsDSU | ||||
| Old Silver | Easy | Show TagsDSU | ||||
| CSA | Medium | Show TagsDSU | ||||
| CF | Medium | Show TagsDSU | ||||
| Gold | Medium | Show TagsDSU | ||||
较难
如果这是你第一次接触 DSU,不必急着解决这些题目。
| Status | Source | Problem Name | Difficulty | Tags | ||
|---|---|---|---|---|---|---|
| CSES | Hard | Show TagsDSU, Merging | ||||
| Gold | Hard | Show TagsDSU, Merging, Sorted Set | ||||
| Old Gold | Hard | Show TagsDSU | ||||
| onlinejudge.org | Hard | Show TagsDSU | ||||
| Baltic OI | Very Hard | Show TagsDSU | ||||
| Gold | Very Hard | Show TagsDSU | ||||
| Platinum | Very Hard | Show TagsDSU | ||||