【并查集】hdu 2818

这题算是并查集的变形,每个blocks需要记录三个信息分别是under(位于x以下的个数),cnt(该block所在堆的积木个数),fa(父亲是谁,注意这个父亲是位于当前block的下面那个)。接着就利用并查集的压缩路径回溯时更新under数组。


#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <time.h>
#include <cstdio>
#include <math.h>
#include <iomanip>
#include <cstdlib>
#include <limits.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

#define LL long long
#define MIN INT_MIN
#define MAX INT_MAX
#define pii pair<int ,int>
#define mp make_pair
#define bug cout<<"here!!"<<endl
#define PI acos(-1.0)
#define FRE freopen("input.txt","r",stdin)
#define FF freopen("output.txt","w",stdout)
#define N 30005
int fa[N],under[N],cnt[N];
void init(int x){
    under[x]=0;
    cnt[x]=1;
    fa[x]=x;
}
int find(int x){//压缩路径,利用回溯
    int t;
    if(x!=fa[x]){
        t = find(fa[x]);
        under[x]+=under[fa[x]];
        fa[x]=t;
    }
    return fa[x];
}
void uni(int x,int y){
    int xx = find(x);
    int yy = find(y);
    if(xx!=yy){//不在同一个堆
        under[xx]=cnt[yy];
        cnt[yy]+=cnt[xx];
        fa[xx]=yy;
    }
}
int main(){
    int n;
    scanf("%d",&n);
    int i;
    for(i=0;i<N;i++)init(i);
    while(n--){
        char str[2];
        scanf("%s",str);
        if(str[0]=='M'){
            int x,y;
            scanf("%d%d",&x,&y);
            uni(x,y);
        } else {
            int x;
            scanf("%d",&x);
            find(x);//这里还要更新一下,以防中间的block没有更新
            printf("%d\n",under[x]);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值