poj1988cube stacking(并查集)

本文介绍了一种使用并查集数据结构解决特定栈操作问题的方法。问题涉及最多30000个栈(箱子),需处理这些栈的合并及查询栈中元素数量的操作。文章提供了详细的代码实现,包括如何通过递归方式更新并查集中的父节点和子节点的关系,以及如何计算特定栈中的元素数量。

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

题意:有最多30000个编号为1~30000的箱子,将每个箱子当做一个栈,对这些箱子进行p次操作,每次操作分别为以下两种之一:
1>输入 M x y:表示将编号为x的箱子所在的栈放在编号为y的箱子所在栈的栈顶.
2>输入 C x:计算编号为x的所表示的栈中在x号箱子下面的箱子数目.

这道我想了两天都没想出来,刚接触并查集,完全没想到(弱爆了)在find中使用递归(之前看的都是用循环写的)。

如果下面的代码看不懂可先看并查集的递归写法

int find(int node)
{
    if(pre[node]==node) return node;
    return pre[node]=find(pre[node]);
}
void join(int x,int y)
{
    int fx=find(x),fy=find(y);
    if(fx!=fy) pre[fx]=fy;
}
    pre[node]=find(tmp);
    place[node]+=place[tmp];

这两句是最精华的,主要思考这两句话

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define ms(X) memset(X,0,sizeof(X))
#define msc(X) memset(X,-1,sizeof(X))
typedef long long LL;
using namespace std;
int pre[30005],sum[30005],place[30005];
int find(int node)
{
    if(pre[node]==-1) return node;
    int tmp=pre[node];
    pre[node]=find(tmp);//
    place[node]+=place[tmp];//
    return pre[node];
}
void join(int x,int y)
{
    int fx=find(x),fy=find(y);
    pre[fx]=fy;
    place[fx]+=sum[fy];
    sum[fy]+=sum[fx];
}
int main()
{
    int P;
    cin>>P;
    msc(pre);
    ms(place);
    for(int i=1;i<=30000;i++) sum[i]=1;
    while(P--)
    {
        char ss[3];
        int a,b;
        scanf("%s",ss);
        if(ss[0]=='M'){
            scanf("%d %d",&a,&b);
            join(a,b);
        }
        else {
            scanf("%d",&a);
            find(a);
            printf("%d\n",place[a]);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值