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

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

相关推荐
干炒 牛河2 小时前
数据结构:哈希表
数据结构·算法·散列表
慕容晓开7 小时前
c++,优先队列
数据结构·c++·算法
Lin屿9 小时前
【二分查找】_240. 搜索二维矩阵 II
数据结构·python
笑鸿的学习笔记10 小时前
leetcode-442.数组中重复的数据
数据结构·算法·leetcode
醉城夜风~10 小时前
[数据结构]单值二叉树
数据结构·算法
刃神太酷啦10 小时前
C++(蓝桥杯常考点)
数据结构·c++·蓝桥杯c++组
星空露珠10 小时前
迷你世界脚本世界接口:World
数据结构·游戏·lua
星空露珠11 小时前
迷你世界脚本方块接口:Block
数据结构·游戏·lua
柃歌11 小时前
【UCB CS 61B SP24】Lecture 19 & 20: Hashing & Hashing II 学习笔记
java·数据结构·笔记·学习·算法
HBryce2411 小时前
《数据结构》
java·数据结构