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。
给定一行木块,每堆一个木块,从左到右标号分别为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 1568
- HDU1290
- HDU1568(Fobonacci公式)
- HDU ACM Step 2.2.2 Joseph(约瑟夫环问题)
- HDU 1405
- HDU 1297
- hdu 1205
- hdu 2087
- hdu 1016
- HDU 4898 The Revenge of the Princess’ Knight ( 2014 Multi-University Training Contest 4 )
- HDU 1000
- HDU 1001
- HDU 1622 Trees On The Level
- HDU 1063 Exponentiation
- 杭电1870 愚人节的礼物
- 关于杭电1405 The Last Practice 的问题
- Hdu5033
- HDU 1166 敌兵布阵
- hdu-1103 模拟题。
- hdu-1022 栈的应用。