uva1329 Corporative Network(并查集:路径压缩)

题意:初始时有n个点(编号1到n),每个点都没有父节点,然后依次执行下面两条命令:

        I u v :把节点u的父亲设置为v,并且设u节点到v的距离为|u-v|%1000,输入保证执行I命令的时候,u没有父节点。

        E u:查询u节点到根节点的距离。

        输入:首先是T,表示实例个数。每个实例第一行是n(5<=n<=20000),接下有不超过200000行,每行一个指令,以单独的O字母行表示结束。

        输出:对于每条E指令,输出查询结果。

思路:并查集+路径压缩维护距离值


#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 20010
#define LL long long
int cas=1,T;
int pre[maxn];
int dist[maxn];
int n;
void init()
{
	for (int i = 0;i<=n;i++)
	{
		pre[i]=i;
		dist[i]=0;
	}
}
int Find(int x)
{
	if (x!=pre[x])
	{
        int f = pre[x];
		pre[x]=Find(pre[x]);
		dist[x]+=dist[f];
		return pre[x];
	}
	else
		return x;
//	return pre[x];
}
int main()
{
	//freopen("in","r",stdin);
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n);
		init();
		char str[10];
		while (scanf("%s",str))
		{
			int a,b;
			if (str[0] == 'O')
				break;
			if (str[0] == 'I')
			{
                scanf("%d%d",&a,&b);
				pre[a]=b;
                dist[a]=abs(a-b)%1000;
			}
			if (str[0] == 'E')
			{
                scanf("%d",&a);
				Find(a);
				printf("%d\n",dist[a]);
			}
		}
	}
	//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值