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;
}



目录
相关文章
|
9月前
GEE错误——Layer error: Image.connectedPixelCount: Segment size calculation on floating point bands is n
GEE错误——Layer error: Image.connectedPixelCount: Segment size calculation on floating point bands is n
95 0
|
9月前
Strange fuction(HDU--2899)
Strange fuction(HDU--2899)
UVa 374 Big Mod
UVa 374 Big Mod
45 0
|
机器学习/深度学习 网络架构
PTA 1164-1167 Good in C/Block Reversing/Summit/Cartesian Tree(一)
PTA 1164-1167 Good in C/Block Reversing/Summit/Cartesian Tree
122 0
PTA 1164-1167 Good in C/Block Reversing/Summit/Cartesian Tree(一)
|
机器学习/深度学习 网络架构
PTA 1164-1167 Good in C/Block Reversing/Summit/Cartesian Tree(二)
PTA 1164-1167 Good in C/Block Reversing/Summit/Cartesian Tree
134 0
|
人工智能 BI
CF1169C. Increasing by Modulo(二分)
CF1169C. Increasing by Modulo(二分)
142 0
|
存储 算法
PAT (Advanced Level) Practice - 1151 LCA in a Binary Tree(30 分)
PAT (Advanced Level) Practice - 1151 LCA in a Binary Tree(30 分)
136 0
|
Web App开发 Java 数据安全/隐私保护
HDOJ(HDU) 1563 Find your present!(异或)
HDOJ(HDU) 1563 Find your present!(异或)
248 0