uva 1329 Corporative Network

题意:  有个很大的网络发展,现在有n个独立的结点。输入一串命令,如果是E u 就查询u到他的根结点的距离,如果是I u v,就让v做u的父节点,距离为u-v的绝对值模1000。
分析:并查集问题,比较简单,在find函数记录a【x】的累加。
代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

int a[20005];
int per[20005];
int n;
void init(int n)
{
    for(int i = 1; i <= n; i++)
    {
        per[i] = i;
    }
}
int find(int x)
{
    if(x == per[x]) return x;
    int m = find(per[x]);
    a[x] += a[per[x]];
    per[x] = m;
    return m;
}
int main()
{
    int t; cin >> t;
    while(t--)
    {
        memset(a, 0, sizeof(a));
        cin >> n;
        init(n);
        char c;
        while(cin >> c && c != '0')
        {
            if(c == 'E'){
                int m; cin >> m;
                find(m);
                cout << a[m] << endl;
            }
            if(c == 'I'){
                int x, y, p; cin >> x >> y;
                if(x > y) p = x-y;
                else p = y-x;
                per[x] = y;
                a[x] += p%1000;
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值