Cube Stacking 【POJ - 1988】【并查集(带权并查集)】

版权声明:https://blog.csdn.net/qq_41730082 https://blog.csdn.net/qq_41730082/article/details/85090692

题目链接


  题意就是给你一串箱子,题目中没有给出箱子的数量,问你经过一系列移动之后,某个ID箱子下面有几个箱子,然后移动是把这一整列都按照原来的顺序放在另一列的顶端上去。

  所以,我想到了用并查集来写,对于一个箱子,我们把它放到另一列箱子的上面,我们可以维护下这一列有多少箱子,以及这个箱子之上有多少箱子不包括自己的),然后,我们所要求的其下的箱子的个数就是“总的这一列的箱子数-其上的箱子数-1”,多减一个“1”是为了减去自己。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define efs 1e-7
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 3e4 + 7;
int N, root[maxN], sum[maxN], num[maxN];   //sum是此时的值,num是总和
int fid(int x)
{
    if(x == root[x]) return x;
    int tmp = root[x];
    root[x] = fid(root[x]);
    sum[x] = sum[x] + sum[tmp];
    return root[x];
}
void mix(int x, int y)
{
    int u = fid(x), v = fid(y);
    if(u != v)
    {
        sum[v] = num[u];
        root[v] = u;
        num[u] += num[v];
    }
}
void init()
{
    for(int i=0; i<maxN; i++) { root[i] = i; sum[i] = 0; num[i] = 1; }
}
int main()
{
    while(scanf("%d", &N)!=EOF)
    {
        init();
        while(N--)
        {
            char op[3];
            int x, y;
            scanf("%s", op);
            if(op[0] == 'M')
            {
                scanf("%d%d", &x, &y);
                mix(x, y);
            }
            else
            {
                scanf("%d", &x);
                printf("%d\n", num[fid(x)] - sum[x] - 1);
            }
        }
    }
    return 0;
}
/*
4
M 1 6
M 2 4
M 2 6
C 1
 ans = 1;(Accept)
*/

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/85090692