UVa 1329 Corporative Network(带权并查集)

题目链接:UVa 1329  Corporative Network

做过一个类似的题目吧,现在才知道这叫做带权并查集。d[i]记录节点i到父节点的距离,查询的时候父节点在变,所以数组的值也在改变。

#include <iostream>
#include <cstdio>
//#include <cmath>
#include <algorithm>

using namespace std;

const int MAX_N = 20000 + 100;
int p[MAX_N], d[MAX_N];

int _find(int x)
{
    if(p[x] != x)
    {
        int root = _find(p[x]);
        d[x] += d[p[x]];
        return p[x] = root;
    }
    else
        return x;

}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        int n, u, v;
        char str[3];
        scanf("%d", &n);
        for(int i = 0; i <= n; i++)
            p[i] = i, d[i] = 0;
        while(scanf("%s", str), str[0] != 'O')
        {
            if(str[0] == 'E')
            {
                scanf("%d", &u);
                _find(u);
                printf("%d\n", d[u]);
            }
            else if(str[0] == 'I')
            {
                scanf("%d%d", &u, &v);
                p[u] = v;
                d[u] = abs(u - v) % 1000;
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值