HDU3635 Dragon Balls(并查集)

题意:

n个城市中有n个龙珠,一开始按顺序排列,但龙珠会转移,输入T A B 代表现在龙珠A所在城市中的所有龙珠都转移到龙珠B所在的城市中,Q A 代表查询龙珠A的所在城市和城市中有多少龙珠以及龙珠A转移了多少次

要点:

其他不难,主要是查询龙珠A转移了几次这一步比较难,因为我们进行了状态压缩,所以每次只要根节点会增加转移数,而其子树中所有结点都是不增加的。所以我们另设一个数组来记录转移数,状态压缩时,将q的父节点的转移数添加到q的转移数中即可。注意这里用了爷爷状态压缩法,这种压缩法不如递归压缩法压的多。递归压缩法是将每个节点都指向根节点,而爷爷转移法只能保证压到log(n)。


16674513 2016-03-26 10:10:19 Accepted 3635 873MS 1832K 1187 B C++ seasonal
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 10050
int m,n;
int p[maxn], num[maxn],count[maxn];

void init()
{
	for (int i = 1; i <= m; i++)
	{
		p[i] = i;
		num[i] = 1;
		count[i] = 0;
	}
}
int find(int x)
{
	while (p[x] != p[p[x]])//如果q不是其所在子树的根节点的直接孩子
	{
		count[x] += count[p[x]];//更新数组,将q的父节点的转移数添加到q的转移数中
		p[x] = p[p[x]];//压缩其父节点到其爷爷节点的路径
	}
	return p[x];
}
void merge(int x, int y)
{
	x = find(x);
	y = find(y);
	if (x == y) return;
	else
	{
		p[x] = y;
		num[y] += num[x];//记录转移的集合个数
		count[x]++;//根节点转移数+1,但其中它的孩子的转移数均未增加
	}
}
void print(int x)
{
	int xx = find(x);//count数组是延后的,要得到准确的count[x]前必须进行一次find
	printf("%d %d %d\n", xx, num[xx], count[x]);
}

int main()
{
	int t, x, y, i, q, kase = 1;
	char str;
	scanf("%d", &t);
	while (t--)
	{
		printf("Case %d:\n", kase++);
		scanf("%d%d", &m, &n);
		init();
		while (n--)
		{
			getchar();//清除缓冲区中的\n
			scanf("%c", &str);
			switch (str)
			{
				case 'T': {
					scanf("%d%d", &x, &y); 
					merge(x, y); 
					break; 
				}
				case 'Q':{
					scanf("%d", &q);
					print(q);
				}
			}
		}

	}
	return 0;
}


posted @ 2016-03-26 10:32  seasonal  阅读(131)  评论(0编辑  收藏  举报