flowchart TD
A[Initialize parent rank] --> B[find x with compression]
B --> C[find y with compression]
C --> D{same root}
D -- Yes --> E[Already connected]
D -- No --> F[Union by rank]
F --> G[Attach shallow tree under deep]
G --> H[Optionally increase rank]
H --> I[Connectivity queries become fast]
sequenceDiagram
participant U as union(x,y)
participant FX as find(x)
participant FY as find(y)
participant P as parent[]
U->>FX: root of x
U->>FY: root of y
FX->>P: path compression
FY->>P: path compression
U->>P: union by rank update
# [Union-Find 템플릿: 아키텍트 버전]# Use Case: 집합 합치기, 연결 요소 판별, 크루스칼 알고리즘# Components: Parent Array, Rank Array (최적화)# Constraint: Path Compression + Union by RankclassUnionFind:def__init__(self,n):# 1. 초기화 (Initialization Layer)# - 각 노드가 자기 자신을 부모로self.parent=list(range(n))self.rank=[0]*n# 2. Find 연산 (Find Operation)# - 경로 압축(Path Compression) 적용deffind(self,x):ifself.parent[x]!=x:self.parent[x]=self.find(self.parent[x])# 경로 압축returnself.parent[x]# 3. Union 연산 (Union Operation)# - Rank 기반 합치기defunion(self,x,y):root_x=self.find(x)root_y=self.find(y)ifroot_x==root_y:returnFalse# 이미 같은 집합# 4. Rank 비교 (Union by Rank)ifself.rank[root_x]<self.rank[root_y]:self.parent[root_x]=root_yelifself.rank[root_x]>self.rank[root_y]:self.parent[root_y]=root_xelse:self.parent[root_y]=root_xself.rank[root_x]+=1returnTrue# 5. 연결 여부 확인 (Connected Check)defis_connected(self,x,y):returnself.find(x)==self.find(y)