UVA 1329 Corporative Network【并查集】

2021-07-17 17:06

阅读:681

题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4075

题意:
有n个结点,開始都是单独的结点,如今有I操作和E操作,I u v表示吧u的父亲结点设为,距离为|u - v| % 1000,E操作询问u到根的距离

代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

int fa[1000010];
int d[1000010];

int fd(int x)
{
    if (fa[x] != -1)
    {
        int rot = fd(fa[x]);
        d[x] += d[fa[x]];
        return fa[x] = fd(fa[x]);
    }
    else return x;
}

int main()
{
    int a, b;
    int t, n;
    scanf("%d",&t);
    char cmd[10];
    while (t--)
    {
        memset(fa, -1, sizeof(fa));
        memset(d,0,sizeof(d));
        scanf("%d", &n);
        while (scanf("%s", cmd) && cmd[0] != ‘O‘)
        {
            if (cmd[0] == ‘E‘)
            {
                scanf("%d", &a);
                fd(a);
                printf("%d\n", d[a]);
            }
            else
            {
                scanf("%d%d", &a, &b);
                fa[a] = b;
                d[a] = abs(a - b) % 1000;
            }
        }
    }
    return 0;
}


评论


亲,登录后才可以留言!