UVA - 1329 Corporative Network

本文介绍了一种基于并查集的数据结构实现方法,并在此基础上加入了路径压缩优化。该算法适用于处理一系列节点间的连接和查询操作,特别是对于寻找某个节点到根节点的距离问题。通过示例代码展示了具体的实现细节。

题意:有n个节点,初始话每个节点的父节点都是不存在的,你的任务是执行I或者E操作

I:u,v将u的父节点设为v ,距离为|u-v|%1000; E:询问u到根节点的距离

输出每条E操作

思路:在并查集的基础上加上路径的压缩

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int mod = 1000;
const int MAXN = 20005;

int d[MAXN],f[MAXN],n;

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

int main(){
    int t;
    scanf("%d",&t);
    while (t--){
        scanf("%d",&n);
        for (int i = 0; i <= n; i++)
            f[i] = i,d[i] = 0;
        int u,v;
        char op;
        while (cin >> op && op != 'O'){
            if (op == 'I'){
                scanf("%d%d",&u,&v);
                f[u] = v;
                d[u] = abs(u-v) % mod;
            }
            else {
                scanf("%d",&u);
                find(u);
                printf("%d\n",d[u]);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值