hdu 2818 Building Block(加权并查集)

本文介绍了一种解决树形结构合并问题的高效算法,通过使用路径压缩和按秩合并优化了查找、合并和统计树的大小操作。具体而言,文章详细阐述了如何通过将树中的节点进行合并,并维护节点之间的顺序关系和树的大小信息,从而实现在O(log n)的时间复杂度内完成一系列操作。此外,还提供了具体的代码实现和实例演示,以便读者能够快速理解并应用到实际问题中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意翻译过来就是:开始有n棵树,每棵树的大小为1,然后做一些合并操作,同时要维护一个顺序关系和树的size。。

将C X Y 中的Y作为新的父亲就好做了。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
#define REP(i,s,t) for(int (i)=(s);(i)<=(t);++(i))
typedef long long LL;
const int maxn = 30000;

int pa[maxn+5];
int under[maxn+5];
int tot[maxn+5];

int find(int x) {
    if (x == pa[x]) return pa[x];
    int t = pa[x];
    pa[x] = find(t);
    under[x] += under[t];
    return pa[x];
}

int main() {
    freopen("input.in", "r", stdin);
    char buf[100];
    int x, y, n;
    cin >> n;
    REP(i, 0, maxn) {pa[i] = i;under[i] = 0;tot[i] = 1;}
    while (n--) {
        scanf("%s",buf);
        if (buf[0] == 'M') {
            scanf("%d%d",&x,&y);
            int fx = find(x), fy = find(y);
            if (fx != fy) {
                under[fx] = tot[fy];
                pa[fx] = fy;
                tot[fy] += tot[fx];
            }
        }
        else {
            scanf("%d",&x);
            find(x);
            printf("%d\n",under[x]);
        }
    }
/*
    REP(i, 1, 6) find(i);
    REP(i, 1, 6) cout << under[i] << ' ';cout << endl;
    REP(i, 1, 6) cout << tot[i] << ' ';cout << endl;
    REP(i, 1, 6) cout << pa[i] << ' ';cout << endl;
*/
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值