数据结构——并查集

AcWing - 算法基础课

Acwing------合并集合

代码如下:

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;
#define fs first
#define sc second
#define endl '\n'
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;

const int N = 1e5+10;

int p[N];

int find(int x)
{
	if(x==p[x])return x;//找到根了x==p[x]
	//否则压缩路径 把节点直接指向老祖宗(优化)
	else p[x]=find(p[x]);
}

void solve(){
    int n,m;
    cin>>n>>m;
    
    for(int i=1;i<=n;i++)p[i]=i;//初始化(每个人都是自己的祖宗)
    
    for(int i=0;i<m;i++)
    {
    	char x;cin>>x;
    	int a,b;
    	if(x=='M')
    	{
    		cin>>a>>b;
    		p[find(a)]=find(b);//两个集合合并
    	}
    	else{
    		cin>>a>>b;
    		if(find(a)==find(b))puts("Yes");
    		else puts("No");
    	}
    }
}

int main(){
	
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(0);

    int t;
    t=1;

    while (t--)
    {
        solve();
    }
    
    return 0;
}
相关推荐
2301_7644413324 分钟前
使用python构建的应急物资代储博弈模型
开发语言·python·算法
小熳芋27 分钟前
验证二叉搜索树- python-递归&上下界约束
数据结构
hetao17338371 小时前
2025-12-11 hetao1733837的刷题笔记
c++·笔记·算法
Xの哲學1 小时前
Linux电源管理深度剖析
linux·服务器·算法·架构·边缘计算
小飞Coding1 小时前
一文讲透 TF-IDF:如何用一个向量“代表”一篇文章?
算法
算家计算1 小时前
突然发布!GPT-5.2深夜来袭,3个版本碾压人类专家,打工人该怎么选?
算法·openai·ai编程
s09071362 小时前
Xilinx FPGA 中ADC 数据下变频+ CIC 滤波
算法·fpga开发·fpga·zynq
TL滕3 小时前
从0开始学算法——第十二天(KMP算法练习)
笔记·学习·算法
Math_teacher_fan3 小时前
第二篇:核心几何工具类详解
人工智能·算法
汉克老师3 小时前
CCF-NOI2025第二试题目与解析(第二题、集合(set))
c++·算法·noi·子集卷积·sos dp·mod 异常