UVa 1329 Corporative Network(并查集)

题目链接:http://acm.hust.edu.cn/vjudge/problem/36132

大意:给出n个结点,一系列操作。对于操作I,输入u,v,把u的父结点设为v,距离为|u-v|mod1000;对于操作E,输入u,输出u到根结点的距离。

思路:两个操作正好对应了并查集的合并和查找,对于操作I,由于v没有父结点,直接令pre[u] = v即可;对于操作E,由于根节点是动态变化的,所以要先更新再查询。


#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 2e4 + 5;
int n, pre[maxn], dist[maxn];

int find(int x)
{
    if (pre[x] == x) return pre[x];
    int y = pre[x];
    pre[x] = find(pre[x]);
    dist[x] += dist[y];
    return pre[x];
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%d",&n);
        memset(dist, 0, sizeof dist);
        for(int i = 1; i <= n; i++) pre[i] = i;
        char s[2];
        while(scanf("%s",s) && s[0] != 'O') {
            if (s[0] == 'E') {
                int x;
                scanf("%d",&x);
                find(x);
                printf("%d\n",dist[x]);
            }
            else {
                int a,b;
                scanf("%d%d",&a,&b);
                pre[a] = b;
                dist[a] = abs(a-b) % 1000;
            }
        }
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值