#define N 1000
int pre[N]; //每个结点
int rank[N]; //树的高度
int Init(int n) //对n个结点初始化
{
for(int i = 0; i < n; i++)
{
pre[i] = i; //每个结点的上级都是自己, 也可以设置为-1
rank[i] = 1; //每个结点构成的树的高度为1
}
}
//查找根节点也可以使用while循环
int Find(int x) //查找结点x的根结点
{
if(pre[x] == x)
{
//递归出口:x的上级为x本身,即x为根结点,如果设置的-1,递归出口就是==-1
return x;
}
return Find(pre[x]); //递归查找
}
//改进查找算法:完成路径压缩,将x的上级直接变为根结点,那么树的高度就会大大降低
int Find_Pre(int x) //查找结点x的根结点
{
if(pre[x] == x)
{
//递归出口:x的上级为x本身,即x为根结点
return x;
}
return pre[x] = Find_Pre(pre[x]); //路径压缩
}
bool Is_Same(int x, int y) //判断两个结点是否连通
{
return Find_Pre(x) == Find_Pre(y); //判断两个结点的根结点是否相同
}
void unite(int x,int y)
{
int rootx, rooty;
rootx = Find_Pre(x);
rooty = Find_Pre(y);
if(rootx == rooty)
{
return ;
}
if(rank[rootx] > rank[rooty])
{
//令高度大的作为高度小的根节点,这样下次查找的次数会少一点
pre[rooty] = rootx; //令y的根结点的上级为rootx
}
else
{
if(rank[rootx] == rank[rooty])//若高度相同,则作为根节点的那个高度+1
{
rank[rooty]++;
}
pre[rootx] = rooty;
}
}
int main()
{
return 0;
}