合作网络(Corporative Network)(带权并查集)

题目大意:

n个结点,初始时每个结点的父节点都不存在,两种操作:

I u v : 把u的父亲设为v,距离为|u-v| mod 1000

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

#include <iostream>
#include <cmath>
#include <stdio.h> 
using namespace std;
const int maxn=20010;
int father[maxn],dis[maxn];
int find(int x)
{
	if(father[x]!=x)
	{
		int num=find(father[x]);
		dis[x]+=dis[father[x]];
		return father[x]=num;
	}
	else
	return x;
}
int main(){
	int t,n;
	cin>>t;
	while(t--)
	{
		scanf("%d",&n);
		int x,y;
		for(int i=1;i<=n;i++)
		{
			dis[i]=0;
			father[i]=i;
		}
		char wzx[10];
		while(scanf("%s",wzx)&&wzx[0]!='O')
		{
			if(wzx[0]=='E')
			{
				scanf("%d",&x);
				find(x);
				printf("%d\n",dis[x]);
			}
			else
			{
				scanf("%d%d",&x,&y);
				father[x]=y;
				dis[x]=abs(x-y)%1000;
			}
		}
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值