Union-find root lookup
Find a representative using path halving.
| Root | parent[x] = x | Initialize each node as its own root |
| Union | Attach smaller root | Update size only on surviving root |
Python
def find(p,x):
while p[x]!=x:
p[x]=p[p[x]]
x=p[x]
return xC++
int find(std::vector<int>& p,int x){while(p[x]!=x){p[x]=p[p[x]];x=p[x];}return x;}Java
static int find(int[] p,int x){while(p[x]!=x){p[x]=p[p[x]];x=p[x];}return x;}