跳到正文

算法·理论

并查集的按大小合并时间复杂度证明

lzyqwq约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

可能比较粗糙。

我们要证明一个大小为 nn 的连通块深度(最远的点到根的边数)至多为 ⌊log⁡2n⌋\lfloor\log_2 n\rfloor。记一个连通块 AA 的深度为 depA\text{dep}_A,则要求证:∀ A(∣A∣=n),depA≤⌊log⁡2n⌋\forall \,A(|A|=n),\text{dep}_A\le \lfloor\log_2 n\rfloor。

显然该命题对于 n∈[1,2]⋂Zn\in[1,2]\bigcap \mathbb{Z} 成立。

考虑归纳法,假设该命题对于 n∈[1,i]⋂Z,i∈[2,+∞)⋂Zn\in[1,i]\bigcap \mathbb{Z},i\in[2,+\infty)\bigcap \mathbb{Z} 成立,则当 n=i+1n=i+1 时,记这个连通块为 WW,设它由两个连通块 U,VU,V 合并得到,满足 ∣U∣+∣V∣=n|U|+|V|=n。不妨令 ∣U∣≥∣V∣|U|\ge|V|,则 VV 合并到 UU 上,depW=max⁡{depU,depV+1}\text{dep}_W=\max\{\text{dep}_U,\text{dep}_V+1\}。

记不超过 nn 的最大的 22 的幂为 2h(n),h(n)∈N+2^{h(n)},h(n)\in\mathbb{N}^+,则有 ⌊log⁡2n⌋=h(n)\lfloor\log_2 n\rfloor=h(n)。

  • 若 nn 为 22 的幂:

    此时 2h(n)−1≤∣U∣<n,0<∣V∣≤2h(n)−12^{h(n)-1}\le |U|<n,0<|V|\le 2^{h(n)-1},有 h(∣U∣)=h(n)−1,h(∣V∣)≤h(n)−1h(|U|)=h(n)-1,h(|V|)\le h(n)-1,所以 depU≤h(n)−1,depV+1≤h(n)\text{dep}_U\le h(n)-1,\text{dep}_V+1\le h(n),因此 depW≤h(n)=⌊log⁡2n⌋\text{dep}_W\le h(n)=\lfloor\log_2n\rfloor。

  • 若 nn 不为 22 的幂:

    • 若 2h(n)≤∣U∣<n,0<∣V∣<2h(n)2^{h(n)}\le |U|<n,0<|V|<2^{h(n)},则 h(∣U∣)=h(n),h(∣V∣)≤h(n)−1h(|U|)=h(n),h(|V|)\le h(n)-1。所以 depU≤h(n),depV+1≤h(n)\text{dep}_U\le h(n),\text{dep}_V+1\le h(n),因此 depW≤h(n)=⌊log⁡2n⌋\text{dep}_W\le h(n)=\lfloor \log_2n\rfloor。

    • 若 0<∣V∣≤∣U∣<2h(n)0<|V|\le |U|<2^{h(n)},则 h(∣V∣)≤h(∣U∣)≤h(n)−1h(|V|)\le h(|U|)\le h(n)-1,所以 depU≤h(n)−1,depV+1≤h(n)\text{dep}_U\le h(n)-1,\text{dep}_V+1\le h(n),因此 depW≤h(n)=⌊log⁡2n⌋\text{dep}_W\le h(n)=\lfloor \log_2n\rfloor。

证毕。

原文