UVALive - 3027Corporative Network(带权并查集)

本文介绍了解决UVALive-3027问题的方法,该问题涉及带权并查集的数据结构操作。具体地,文章详细解释了如何通过更新节点间的相对距离来维护树状结构,并提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: UVALive - 3027Corporative Network(带权并查集)


题目大意:有n和节点,初始时每个节点的父节点都不存在,然后有下面两种操作:I 操作 I a,b 将a的父节点变成b。E操作 E a,查询a到它的父节点的距离。


解题思路:带权并查集。注意这里距离的变化是a -> b,那么a到根节点的距离就是a到b的距离的绝对值 % 1000 + b到它的根节点的距离。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 2e5 + 5;
int p[maxn], c[maxn];
int n;

void init () {
	
	for (int i = 1; i <= n; i++) {
		p[i] = i;
		c[i] = 0;
	}
}

int getParent (int a) {
	
	if (a == p[a])
		return a;
	int t = p[a];
	p[a] = getParent (p[a]);
	c[a] += c[t];	
	return p[a];
}

int main () {

	int T;
	int a, b;
	char str[10];
	scanf ("%d", &T);
	while (T--) {

		scanf ("%d", &n);
		init();
		while (scanf ("%s", str) != EOF) {
			
			if (str[0] == 'O')
				break;
			if (str[0] == 'E') {

				scanf ("%d", &a);
				int q1 = getParent (a);
				printf ("%d\n", c[a]);
			} else {

				scanf ("%d%d", &a, &b);
				p[a] = b;
				c[a] = abs (a - b) % 1000;
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值