Template
1. Initialization
2. Find the root node
3. Merging
int per[1100];void init () {for (int i =1; I <= N; ++i) Per[i] = i;//initialization At first each node is independent of the parent node is itself}int find (int x) {if (x = = Per[x])//recursive return X;return per[x] = find (Per[x]);} can be shortened into//return x==per[x]?X:per[x]=find (Per[x]); void join (int x, int y) {//merge two nodes int fx = find (x); int fy = find (y); if (FX! = FY)//Assume X. The root node of y is different per[fx] = fy;//Connect two root nodes}//as to which node to connect to, look at depth, can open the number of groups. It is an optimal way to connect a small depth to a large depth. When the data is big, it can be enough
The Find function looks for the root node and there are two ways to implement it:
int find (int x) {int r = x;while (r! = Per[r]) R = per[r];//update node until R=per[r] (parent node of root node is itself) int I, j;i = X;while (i! = r) {// Path compression j = per[i];//Save the next node, that is, the parent node of the current node per[i] = r;//assigns the parent node of the current node to the root node i = j;//update node}return r;//returns the root node} //or int find (in T x) {int r = x;while (r! = Per[r]) R = per[r];p er[x] = r;//make R the parent of x one step}
The following are recursive optimized path merges:
void join (int x, int y) { int fx = find (x); int fy = find (y); if (FX = = FY) return; if (Ran[fx] < Ran[fy])//The depth of the small tree to the depth of the number if the depth of the two trees is h1,h2 per[fx] = fy;//The combined number of the height H:max (h1,h2), if H1<>H2 else{ //h1+h2,if h1=h2 per[fy] = FX; if (ran[fx] = = Ran[fy]) ran[fx]++; }}
Algorithm traces---and check set