HDU-3635-Dragon Balls

HDU-3635-Dragon Balls

http://acm.hdu.edu.cn/showproblem.php?pid=3635

并查集,路径压缩来更新转移的次数

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
#define N 10005
struct cam
{
	int f;
	int num;
	int cnt;
}list[N];
int n;
int find(int x) //查询父亲结点,并且加上转移的次数
{
	int temp;
	if(x!=list[x].f)
	{
		temp=list[x].f;
		list[x].f=find(temp);
		list[x].cnt+=list[temp].cnt;
	}
	return list[x].f;
}
void merege(int x,int y)   //将x转至y
{
	int xx,yy;
	xx=find(x);
	yy=find(y);
	if(xx==yy)
	return;
	list[xx].f=yy;
	list[yy].num+=list[xx].num;
	list[xx].cnt++;  //根节点加1
}
int main()
{
	int k,t,q,i,m;
	int a,b;
	char ch;
	scanf("%d",&t);
	for(k=1;k<=t;k++)
	{
		scanf("%d%d",&n,&q);
		for(i=1;i<=n;i++)
		{
			list[i].f=i;
			list[i].num=1;
			list[i].cnt=0;
		}
	    printf("Case %d:\n",k);
		while(q--)
		{
			getchar();
			scanf("%c",&ch);
			if(ch=='T')
			{
				scanf("%d %d",&a,&b);
				merege(a,b);
			}
			else
			{
				scanf("%d",&a);
				m=find(a);
				printf("%d %d %d\n",list[m].f,list[m].num,list[a].cnt);
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值