The main functions:
int Find ( int X) { int R & lt = X; the while (! R & lt = pre [R & lt]) R & lt = pre [R & lt]; } void the Join ( int X, int Y) { int FX = Find (X), FY = Find (Y); IF (! fx = fy) pre [fx] = fy; // the fx fy child node as the else { IF (== fx fy) // equal, to have a ring based } }
:( path compression optimization of recursive recursive optimization can traverse to each node, making back when we can relationship with the child node of the parent node for processing, to solve the weighted disjoint-set is often used in)
But when the data is too large, can not be used, it will MLE error
int find(int x){ if(x==pre[x]) return x; else { int k=pre[x]; pre[x]=find(pre[x]); return fa[x]; } }
Non-recursive compression path
int Find ( int X) { int R & lt = X; the while (! pre [R & lt] = R & lt) { R & lt = pre [R & lt]; } int K = X, J; the while (! K = R & lt) { J = pre [ K]; with j // save the parent node of the current node pre [K] = R & lt; // modify a parent node K = j; } return K; }