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

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

相关推荐
故事和你912 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
破浪前行·吴4 小时前
数据结构概述
数据结构·学习
小欣加油5 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展
我真不是小鱼5 小时前
cpp刷题打卡记录30——轮转数组 & 螺旋矩阵 & 搜索二维矩阵II
数据结构·c++·算法·leetcode
码完就睡9 小时前
数据结构——栈和队列的相互模拟
数据结构
iiiiyu9 小时前
常用API(SimpleDateFormat类 & Calendar类 & JDK8日期 时间 日期时间 & JDK8日期(时区) )
java·大数据·开发语言·数据结构·编程语言
故事和你919 小时前
洛谷-数据结构1-4-图的基本应用2
开发语言·数据结构·算法·深度优先·动态规划·图论
꧁细听勿语情꧂10 小时前
数据结构概念和算法、时间复杂度、空间复杂度引入
c语言·开发语言·数据结构·算法
Felven10 小时前
B. The 67th 6-7 Integer Problem
数据结构·算法
研☆香10 小时前
聊一聊如何分析js中的数据结构
开发语言·javascript·数据结构