Optimization of two disjoint-set (rank path compression optimization +)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_36561697/article/details/96753508

Path compression
using recursion when looking for ancestors, but once the elements of a multiply, or degenerate into a chain, each GetFather will use all the complexity of O (n), which is obviously not what we want. In this regard, we have to be compressed path that we find the most ancient ancestors, "the way" to its descendants directly connected to it. This is the path compressed. Using the path as the compressed code, the time complexity group
present can be considered constant.
Path compression can achieve a simple but some topics will burst stack iterative and recursively recursively.

//递归形式的路径压缩
int getf(int v)
{
    if(v==f[v]) return v;
    return f[v]=getf(f[v]);
}
int find(int x)//非递归写法,不太好记但是更快,列几组数据试一下也不难理解
{
	int r=x,q;
	while(r!=father[r])
		r=father[r];
	while(x!=r)
	{
		q=father[x];
		father[x]=r;
		x=q;
	}
	return r;
}

By rank merge
here can be applied to a simple heuristic strategy - merge by rank. The method uses a rank to represent the upper bound tree height, when combined, will always have a smaller root rank point having a larger root rank. Simply put, it is always relatively low tree as a sub-tree, added to the high tree. In order to preserve the rank, the need for additional use an array with the same length uset, and all the elements are initialized to zero. So look for ancestors will reduce the number of recursive iterations, only the worst logN times.

void Merge(int x,int y)
{
    int t1=getf(x),t2=getf(y);
    if(t1==t2) return ;//已合并返回
    if(rnk[t1]>rnk[t2]) f[t2]=t1;  //把y的祖先t2和并到x的祖先t1上。因以t1为根的树更高
    else {
        f[t1]=t2;
        if(rnk[t1]==rnk[t2]) rnk[t2]++; //若两树一样高,那么合并后,高度加一。
    }
}

 

Guess you like

Origin blog.csdn.net/qq_36561697/article/details/96753508