hdu 2818 Building Block

简介: 点击打开hdu 2818 思路: 带权并查集 分析: 1 题目给定2种指令 M x y把x的集合放在y集合的上面,C x求x的下面有多少个元素 2 我们用rank[x]表示x以下有多少个元素,那么对于指令M x y我们始终把左边的合并到右...

点击打开hdu 2818

思路: 带权并查集
分析:
1 题目给定2种指令 M x y把x的集合放在y集合的上面,C x求x的下面有多少个元素
2 我们用rank[x]表示x以下有多少个元素,那么对于指令M x y我们始终把左边的合并到右边,那么这样rank就满足压缩的性质
3 但是因为这边的合并和普通不一样,它是把x所在的集合放在y所在集合上面,实际上是x的跟节点合并到y集合的最远点,所以我们应该开个数组记录当前集合最远的点

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

const int MAXN = 30010;

int n;
int father[MAXN];
int rank[MAXN];
int maxNum[MAXN];

void init(){
    memset(rank , 0 , sizeof(rank));
    memset(maxNum , 0 , sizeof(maxNum));
    for(int i = 0 ; i < MAXN ; i++)
        father[i] = i;
}

int find(int x){
    if(father[x] != x){
        int fa = father[x];
        father[x] = find(fa);
        rank[x] += rank[fa];
    }
    return father[x];
}

void Union(int x , int y){
    int fx = find(x);
    int fy = find(y);
    if(fx != fy){
        father[fx] = fy; 
        rank[fx] += maxNum[fy]+1;
        maxNum[fy] += maxNum[fx]+1;
    }
}

int main(){
    char c;
    int x , y;
    while(scanf("%d%*c" , &n) != EOF){
         init(); 
         while(n--){
              c = getchar();      
              if(c == 'M'){
                  scanf("%d%d%*C" , &x , &y);
                  Union(x , y);
              }
              else{
                  scanf("%d%*C" , &x);
                  find(x);
                  printf("%d\n" , rank[x]);
              }
         } 
    }
    return 0;
}



目录
相关文章
|
10月前
uva101 The Blocks Problem
uva101 The Blocks Problem
34 0
LeetCode 383. Ransom Note
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
51 0
LeetCode 383. Ransom Note
PAT (Advanced Level) Practice - 1014 Waiting in Line(30 分)
PAT (Advanced Level) Practice - 1014 Waiting in Line(30 分)
99 0
LeetCode之Ransom Note
LeetCode之Ransom Note
95 0
|
Java
[LeetCode] Ransom Note
A very typical application of hash maps. Since I am now learning Java, I code in Java. The following code uses toCharArray() and getOrDefault(), which are learnt from this post.
897 0
【HDU 5572 An Easy Physics Problem】计算几何基础
2015上海区域赛现场赛第5题。 题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5572 题意:在平面上,已知圆(O, R),点B、A(均在圆外),向量V。
1006 0
|
机器学习/深度学习 C++

热门文章

最新文章