算法导论 第21章 21-2 深度确定

一、题目

 

二、代码

/* 
UnionFindSet.h 
并查集,非递归方法,含路径压缩,数组从0开始
*/ 
#include <iostream>   
using namespace std;  
  
#define MAXN 30005  
  
class UFS
{
public:
	int n;
	int p[MAXN+1];//集合根结点
	int rank[MAXN+1];  //集合中点的个数
	int depth[MAXN+1];
public:
	UFS(int size = MAXN);
	void clear();
	int Find_Set(int x);
	//a并入b中,不区分大小
	void Union(int x, int y);
	void Make_Set(int x);
	void Link(int x, int y);
	void Graft(int r, int v);
};
UFS::UFS(int size):n(size)
{
	//必须从0开始
	for(int i = 0; i <= n; i++)  
		Make_Set(i);  
}
void UFS::Make_Set(int x)
{
	p[x] = x;
	rank[x] = 0;
	depth[x] = 0;
}
void UFS::clear()
{
	for(int i = 0; i <= n; i++)  
		Make_Set(i);
}
int UFS::Find_Set(int x)
{
    int temp = x,sum = 0,ans;    
    while(temp != p[temp]) {    
       sum = sum + depth[temp];    
       temp = p[temp];    
    }    
    ans = temp;    
    while(x != ans) {    
       sum -= depth[x];    
       depth[x] += sum;    
       temp = p[x];    
       p[x] = ans;    
       x = temp;    
    }    
    return ans;
}
void UFS::Union(int x, int y)
{
	if(x == y)
		return ;
	Link(x, y);
}
void UFS::Link(int x, int y)
{
	p[x] = y;
	depth[x] = 1;
	rank[y] += rank[x];
}
void UFS::Graft(int r, int v)
{
	int x = Find_Set(r);
	int y = Find_Set(v);
	if(x < y)
		Union(x, y);
	else
		Union(y, x);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值