当前位置:网站首页>AcWing 836. 合并集合(并查集)
AcWing 836. 合并集合(并查集)
2022-04-22 05:35:00 【Ice Cream~】
题目:
一共有 n 个数,编号是 1∼n,最开始每个数各自在一个集合中。
现在要进行 m 个操作,操作共有两种:
M a b,将编号为 a 和 b 的两个数所在的集合合并,如果两个数已经在同一个集合中,则忽略这个操作;Q a b,询问编号为 a 和 b 的两个数是否在同一个集合中;输入格式
第一行输入整数 n 和 m。
接下来 m 行,每行包含一个操作指令,指令为
M a b或Q a b中的一种。输出格式
对于每个询问指令
Q a b,都要输出一个结果,如果 a 和 b 在同一集合内,则输出Yes,否则输出No。每个结果占一行。
数据范围
1≤n,m≤10^5
输入样例:
4 5 M 1 2 M 3 4 Q 1 2 Q 1 3 Q 3 4输出样例:
Yes No Yes
并查集算法解释:

代码实现:
#include<iostream>
using namespace std;
int n,m;
const int N=100010;
int p[N];
int find(int x)//找x的祖宗结点 路径优化
{
if(p[x]!=x)p[x]=find(p[x]);
return p[x];
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)p[i]=i;
while(m--)
{
char op;
int a,b;
cin>>op>>a>>b;
if(op=='M')
{
p[find(a)]=find(b);//a的祖宗的父节点等于b的祖宗结点
}
else if(op=='Q'){
if(find(a)==find(b))cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}
版权声明
本文为[Ice Cream~]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_52797843/article/details/123362480
边栏推荐
猜你喜欢

再见2020,2021我来了

Read write separation of MYCAT

2022 Niuke winter vacation supplementary question record 2

生成excel模板(下拉选、多级联动)

Fundamentals of graphics - Ambient Occlusion

力扣876. 链表的中间结点

Force buckle - 300 Longest increasing subsequence

MySQL index

The unreal engine uses loadclass to load the blueprint class

MySQL transaction
随机推荐
IDEA的安裝与使用技巧
二叉树五个重要性质(附图理解)
Fundamentals of graphics - flood
7.Domino piling
DolphinDB VSCode 插件使用教程
MySQL transaction
顺序存储的二叉树的最近的公共祖先问题|PTA
kibana 搜索语法
list stream: reduce的使用实例
C WinForm about incomplete display of listview
C language version: the pre order, middle order and post order non recursive traversal of binary tree
Fundamentals of graphics - Mobile GPU architecture
Linux下安装Mysql8
Xxxx (dynamic library name): cannot open shared object file: no such file or directory
Array division (backpack)
MySQL函数及练习题(二)
Mysql基础知识
JUC并发编程
[nanny installation tutorial] download MySQL 5 from the source code of Linux operating system seven
MySQL 第7章 对数据表的复杂查询