您的位置:首页 > 产品设计 > UI/UE

HDU 2818 - Building Block

2015-07-21 20:17 393 查看
题意:

给定一行木块,每堆一个木块,从左到右标号分别为1~300000.

针对木块可以执行以下两种操作:

1、M x y 将x所在的木块移到y所在木块的上面。

2、C x 查询x下方的木块数量。

此题想了好久也没有做出来,然后看了一下别人的思路。

利用并查集 + rank数组 + under数组即可搞定。

under数组用来存储当前木块以下的木块个数。

rank数组用来存储当前集合中的总木块个数。



上图所示为执行M 2 6操作,此时应把under[3]改为集合2的元素个数。

并采用路径压缩,将结点2也指向集合2的根结点,并更新under数组。

注意,查询操作之前,要进行一次find操作。

坑点:此题木块编号实际为0~30000。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <ctype.h>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
#include <sstream>

typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int a[300005], rk[300005], under[300005];
void init()
{
for(int i = 0; i <= 300000; i++)
{
under[i] = 0;
a[i] = i;
rk[i] = 1;
}
}
int find(int x)
{
if(x != a[x])
{
int tmp = find(a[x]);
under[x] += under[a[x]];
a[x] = tmp;
}
return a[x];
}
void merge(int x, int y)
{
x = find(x);
y = find(y);
if(x != y)
{
a[x] = y;
under[x] = rk[y];
rk[y] += rk[x];
}
}
int main()
{
int T;
char ch[10];
while(~scanf("%d", &T))
{
init();
for(int i = 0; i < T; i++)
{
scanf("%s", ch);
int x, y;
if(ch[0] == 'M')
{
scanf("%d %d", &x, &y);
merge(x, y);
}
else
{
scanf("%d", &x);
find(x);
printf("%d\n", under[x]);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  杭电 HDU