uva 11987 Almost Union-Find(并查集)

737 篇文章 0 订阅

Almost Union-Find

I hope you know the beautiful Union-Find structure. In this problem, you're to implement something similar, but not identical.

The data structure you need to write is also a collection of disjoint sets, supporting 3 operations:

1 p q

Union the sets containing p and q. If p and q are already in the same set, ignore this command.

2 p q

Move p to the set containing q. If p and q are already in the same set, ignore this command

3 p

Return the number of elements and the sum of elements in the set containing p.

Initially, the collection contains n sets: {1}, {2}, {3}, ..., {n}.

Input

There are several test cases. Each test case begins with a line containing two integers n and m (1<=n,m<=100,000), the number of integers, and the number of commands. Each of the next m lines contains a command. For every operation, 1<=p,q<=n. The input is terminated by end-of-file (EOF). The size of input file does not exceed 5MB.

Output

For each type-3 command, output 2 integers: the number of elements and the sum of elements.

Sample Input

5 7
1 1 2
2 3 4
1 3 5
3 4
2 4 1
3 4
3 3

Output for the Sample Input

3 12
3 7
2 8
题目大意:命令1:将a  b 所在的集合合并 。

命令2:将a   移动到b集合。

命令3:输出a所在集合所有元素的和以及个数。

解题思路:用并查集去做,主要处理的一点就是根进行命令2操作的时候。解决方法就是新增一个不会改变的根,例如:far[i + N] = far[i] = i + N;这样i只向i+ N,移动i时就不会导致下边的指向发生错误。

#include <stdio.h>
#define N 100000
int far[2 * N + 10], sum [N + 10], cnt[N + 10];
int n, m, t, a, b;

int get(int x){
    return x != far[x]?far[x] = get(far[x]):x;
}

int main(){
    while (scanf("%d%d", &n, &m) != EOF){
	// Init;
	for (int i = 1; i <= n; i++){
	    far[N + i] = far[i] = i + N;
	    sum[i] = i;
	    cnt[i] = 1;
	}

	for (int i = 0; i < m; i++){
	    scanf("%d", &t);
	    if (t == 1){
		scanf("%d%d", &a, &b);
		if (get(a) != get(b)){
		    sum[get(b) - N] += sum[get(a) - N];
		    cnt[get(b) - N] += cnt[get(a) - N];
		    far[get(a)] = get(b);
		}
	    }
	    else if (t == 2){
		scanf("%d%d", &a, &b);
		if (get(a) != get(b)){
		    sum[get(a) - N] -= a;
		    cnt[get(a) - N]--;
		    sum[get(b) - N] += a;
		    cnt[get(b) - N]++;
		    far[a] = get(b); 
		}
	    }
	    else{
		scanf("%d", &a);
		printf("%d %d\n", cnt[get(a) - N], sum[get(a) - N]);
	    }
	}
    }
    return 0;}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值