defunion(self, x: int, y: int, w: int) -> bool: rx, ry = self.find(x), self.find(y) dx, dy = self.dis[x], self.dis[y] if rx == ry: # x 和 y 在同一集合,不做合併 return (dy ^ dx) == w
if self.sz[rx] < self.sz[ry]: # fa[rx] = ry # rx <------- ry # | | # | dx | dy # ↓ ↓ # x --------> y # => pot(rx) - pot(ry) = dy - w - dx self.fa[rx] = ry self.dis[rx] = dy ^ w ^ dx self.sz[ry] += self.sz[rx] else: # fa[ry] = rx # rx -------> ry # | | # | dx | dy # ↓ w ↓ # x --------> y # => pot(ry) - pot(rx) = w - dy + dx self.fa[ry] = rx self.dis[ry] = w ^ dy ^ dx self.sz[rx] += self.sz[ry]
returnTrue
classSolution: defnumberOfEdgesAdded(self, n: int, edges: List[List[int]]) -> int: uf = UnionFind(n) ans = 0 for u, v, w in edges: if uf.union(u, v, w & 1): ans += 1 return ans
補充:通用帶權併查集模板(加減法)
適用於一般差值約束 p(y)−p(x)=w 的題目(若為模 k 約束或乘法/除法約束,只需替換對應群運算與反元素即可):
defunion(self, x: int, y: int, w: int) -> bool: """ 合併並加入約束:potential(y) - potential(x) = w 回傳: - True:成功合併(或已同集合且不發生矛盾) - False:已同集合但發生矛盾 """ rx, ry = self.find(x), self.find(y) dx, dy = self.dis[x], self.dis[y] if rx == ry: # x 和 y 在同一集合,不做合併 return (dy - dx) == w
if self.sz[rx] < self.sz[ry]: # fa[rx] = ry # rx <------- ry # | | # | dx | dy # ↓ ↓ # x --------> y # => pot(rx) - pot(ry) = dy - w - dx self.fa[rx] = ry self.dis[rx] = dy - w - dx self.sz[ry] += self.sz[rx] else: # fa[ry] = rx # rx -------> ry # | | # | dx | dy # ↓ w ↓ # x --------> y # => pot(ry) - pot(rx) = w - dy + dx self.fa[ry] = rx self.dis[ry] = w - dy + dx self.sz[rx] += self.sz[ry]
The cover image was created by @D.DCCK. All rights belong to the original artist.
If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.