数据结构——并查集

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;
}
相关推荐
学习中的码虫30 分钟前
数据结构中的高级排序算法
数据结构·算法·排序算法
山北雨夜漫步35 分钟前
机器学习 Day17 朴素贝叶斯算法-----概率论知识
人工智能·算法·机器学习
是店小二呀1 小时前
【优选算法 | 字符串】字符串模拟题精选:思维+实现解析
android·c++·算法
成工小白1 小时前
【Linux】进程地址空间
linux·算法
凤年徐1 小时前
【C/C++】自定义类型:结构体
c语言·开发语言·c++·经验分享·笔记·算法
闪电麦坤952 小时前
数据结构:树(Tree)
数据结构
Inverse1622 小时前
C语言_自定义类型:结构体
c语言·开发语言·算法
Musennn2 小时前
102. 二叉树的层序遍历详解:队列操作与层级分组的核心逻辑
java·数据结构·算法·leetcode
越来越无动于衷3 小时前
java数组题(5)
java·算法
理论最高的吻3 小时前
77. 组合【 力扣(LeetCode) 】
c++·算法·leetcode·深度优先·剪枝·回溯法