hdu 3635 Dragon Balls

题目链接:http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=5&sectionid=1&problemid=10


题意是:有1-n号龙珠分别对应放在1-n号城市,输入T A B时把A号城市的所有龙珠移到B号城市,输入Q A时,输出A号龙珠所在的城市号码,该城市龙珠的数目,A号龙珠一共被移动了多少次。


题目类型:并查集


#include<iostream>
#include<string>
#define max 10005

using namespace std;

int father[max],sum[max],num[max];
void init(int n){
	for(int i = 0;i <= n;i ++){
		father[i] = i;
		sum[i] = 0;
		num[i] = 1;
	}
}

int find(int x){
	int temp;
	if(x == father[x])
		return x;
	else{
		temp = father[x];
		father[x] = find(father[x]);
		sum[x] += sum[temp];
	}
	return father[x];
}

void Union(int a,int b){
	int x = find(a);
	int y = find(b);

	if(x == y) return ;

	else{
		father[x] = y;
		sum[x] ++;
		num[y] += num[x];
		num[x] = 0;
	}
}

int main(){
	const string t = "T";
	string in;
	int cas,n,m,x,y,q;
	int count = 1;
	cin>>cas;

	while(cas --){
		scanf("%d%d",&n,&m);
		init(n);
		printf("Case %d:\n",count++);
		for(int i = 0;i != m;i ++){
			cin>>in;
			if(in == t){
				scanf("%d%d",&x,&y);
				Union(x,y);
			}
			else{
				scanf("%d",&q);
				int loc = find(q);
				printf("%d %d %d\n",loc,num[loc],sum[q]);
			}
		}
	}
	return 0;
}

首先初始化,刚开始每个龙珠的集合就是该龙珠的号码,每个龙珠共被移动次数为0,每个集合含有1个龙珠。

然后是寻找父集合,找的过程中将经过的集合所记录的移动次数全部加起来得到当前集合的移动次数。

并集:若传入的参数a,b不同父集合,把a的父集合并入b的父集合中,就实现了a移到b的要求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值