← 中文资源

简体中文版本

泛型并查集路径压缩

该资源提供 ts-union-find-path-comp-p16 的中文技术参考,涵盖核心方法、参数说明与使用示例

阅读英文原文

实现说明

活动部件是类 UnionFind。

使用要点

  • 守卫 ra === rb 命中后立刻用提前的 return 结束这一轮。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。

核心语句

constructor(n: number) { this.parent = Array.from({ length: n }, (_, i) => i); this.rank = new Array(n).fill(0); this.count = n; }
connected(a: number, b: number): boolean { return this.find(a) === this.find(b); }

代码示例

class UnionFind {
  private parent: number[]; private rank: number[]; count: number;
  constructor(n: number) { this.parent = Array.from({ length: n }, (_, i) => i); this.rank = new Array(n).fill(0); this.count = n; }
  find(x: number): number { while (this.parent[x] !== x) { this.parent[x] = this.parent[this.parent[x]]; x = this.parent[x]; } return x; }
  union(a: number, b: number): boolean { const ra = this.find(a), rb = this.find(b); if (ra === rb) return false; if (this.rank[ra] < this.rank[rb]) this.parent[ra] = rb; else if (this.rank[ra] > this.rank[rb]) this.parent[rb] = ra; else { this.parent[rb] = ra; this.rank[ra]++; } this.count--; return true; }
  connected(a: number, b: number): boolean { return this.find(a) === this.find(b); }
}