2.数据结构:3.合并集合

原题链接

cpp 复制代码
#include<algorithm>
#include<cstring>
#include<iostream>

using namespace std;

const int N=100010;

int p[N];

int find(int x){
    if(p[x]!=x){
        p[x]=find(p[x]);
    }
    return p[x];
}

int main(){
    int n,m;
    cin>>n>>m;
    
    for(int i=1;i<=n;i++){
        p[i]=i;
    }
    
    while(m--){
        char op[2];
        int a,b;
        cin>>op>>a>>b;
        
        if(op[0]=='M'){
            if(find(p[a])!=find(p[b])){
                p[find(a)]=find(b);
            }
        }else{
            if(find(a)==find(b)){
                puts("Yes");
            }else{
                puts("No");
            }
        }
    }
    
    return 0;
}

维护每个点的根节点,合并是修改根节点,查询也是比较根节点。

相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1123 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19433 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww3 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap