HDU3635(Dragon Balls)

题目传送门

在这里插入图片描述

题意

题目说了很多废话,大概就是分两种操作:

  1. T a b就是把a城市的龙珠转移到b城市。
  2. Q a就是查询a龙珠在哪个城市,所属城市目前有多少个龙珠,a龙珠转移了几次到大所属城市。
思路

前面都很好处理,T操作的时候直接把a加到b上就可以,查询操作Q前面两个操作也好找,就并查集找根然后输出根的龙珠数,最最最麻烦的就是转移次数不好确定。既然要查询转移的次数那么我就不进行路径压缩,因为路径压缩会破坏原有的树形结构,所以不进行路径压缩。然后在查询转移次数的时候直接统计该节点向上转移的次数就是了,不过这样复杂度有点点高,因为没有做路径压缩。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 10005;
int s[maxn];
int sum[maxn];
int cnt;
inline void clear_set()
{
	for(int i = 0;i < maxn;i++){
		s[i] = i;
		sum[i] = 1;
	}
}
int find_set(int x)
{
	if(x == s[x]){
		return x;
	}
	cnt++;					//向根节点递归一次转移一次
	return find_set(s[x]);
}
void union_set(int x,int y)
{
	x = find_set(x);
	y = find_set(y);
	if(x != y){
		s[x] = y;
		sum[y] += sum[x];
	}
}
void query(int x)
{
	cnt = 0;
	int r = find_set(x); 
	printf("%d %d %d\n",r,sum[r],cnt);
}
int main()
{
	int t,n,m;
	scanf("%d",&t);
	for(int k = 1;k <= t;k++){
		scanf("%d%d",&n,&m);
		clear_set();
		printf("Case %d:\n",k);
		while(m--){
			char str[5];
			int x,y;
			scanf("%s",str);
			if(str[0] == 'T'){
				scanf("%d%d",&x,&y);
				union_set(x,y);
			}
			else{
				scanf("%d",&x);
				query(x);
			}
		}
	}
	return 0;
}

解法二:

  1. T 1 2 先将1合并到2的时候给t[1]进行转移次数加1。
  2. T 1 3 然后转移1到3的时候实际是把{1,2}转移到3去,但是1的父节点是2,所以把2转移到3上去就好了。然后仅仅对t[2]的转移次数加1,并不更改1的转移次数,现在t[1] = 1,t[2] = 1,t[3] = 0;也就是说我们每次合并的时候只针对根节点的转移次数进行修改,并不对根节点下面的子节点的转移次数进行修改,这样做有什么好处呢?可能很多人的固定思维就是根节点转移了我子节点的转移次数就一定要当场修改好,不当场修改好就难受TvT。
  3. 当每次进行路径查找的时候,由于是向上递归找根节点,找到根节点再逐级往下传递(返回根节点),然后再将父节点的转移次数加给子节点岂不美哉?
    在这里插入图片描述
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 10005;
int s[maxn];
int sum[maxn];
int t[maxn];
int cnt;
inline void clear_set()
{
	for(int i = 0;i < maxn;i++){
		s[i] = i;
		sum[i] = 1;
	}
	memset(t,0,sizeof(t));
}
int find_set(int x)
{
	if(x != s[x]){
		int f = s[x];				
		s[x] = find_set(s[x]);				
		t[x] += t[f];				//将父节点的转移次数加给子节点,子节点在传给子子节点.........
		return s[x];
	}
	return x;
}
void union_set(int x,int y)
{
	x = find_set(x);
	y = find_set(y);
	if(x != y){
		s[x] = y;
		sum[y] += sum[x];
		t[x]++;						//只对根节点的转移次数进行加1修改
	}
}
void query(int x)
{
	cnt = 0;
	int r = find_set(x); 
	printf("%d %d %d\n",r,sum[r],t[x]);
}
int main()
{
	int t,n,m;
	scanf("%d",&t);
	for(int k = 1;k <= t;k++){
		scanf("%d%d",&n,&m);
		clear_set();
		printf("Case %d:\n",k);
		while(m--){
			char str[5];
			int x,y;
			scanf("%s",str);
			if(str[0] == 'T'){
				scanf("%d%d",&x,&y);
				union_set(x,y);
			}
			else{
				scanf("%d",&x);
				query(x);
			}
		}
	}
	return 0;
}

愿你走出半生,归来仍是少年~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值