poj1962 Corporative Network(带权并查集)


http://poj.org/problem?id=1962

题意:给你1-n个点,E x操作代表查询x到根节点的距离,I x y操作代表将x的父节点置为y。


思路:和poj1962有点像,两道题都比较生动ahhh。。值得注意的一点是合并操作时由于计算的是x到根节点的距离,所以直接改变x的父节点以便同步。


#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

typedef long long LL;

const int N = 100010;
const int INF = 0x3f3f3f3f;

int pre[N], dis[N], n;

int Find(int x)
{
    if(x == pre[x]) return x;
    int tmp = pre[x];
    pre[x] = Find(pre[x]);
    dis[x] += dis[tmp];
    return pre[x];
}

void Union(int x, int y)
{
    int rx = Find(x);
    int ry = Find(y);
    pre[x] = ry;
    dis[x] = abs(x-y)%1000+dis[y];
}

void init()
{
    memset(dis, 0, sizeof(dis));
    for(int i = 1; i <= n; i++)
        pre[i] = i;
}

int main()
{
   // freopen("in.txt", "r", stdin);
    int t, x, y;
    char s[5];
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        init();
        while(scanf("%s", s))
        {
            if(s[0] == 'O') break;
            else if(s[0] == 'E')
            {
                scanf("%d", &x);
                Find(x);
                printf("%d\n", dis[x]);
            }
            else if(s[0] == 'I')
            {
                scanf("%d%d", &x, &y);
                Union(x, y);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值