数据结构——并查集

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;
}
相关推荐
bubiyoushang8881 天前
基于MATLAB的马尔科夫链蒙特卡洛(MCMC)模拟实现方法
人工智能·算法·matlab
玖剹1 天前
穷举 VS 暴搜 VS 深搜 VS 回溯 VS 剪枝
c语言·c++·算法·深度优先·剪枝·深度优先遍历
李兆龙的博客1 天前
从一到无穷大 #57:Snowflake的剪枝方案
算法·剪枝
啊我不会诶1 天前
01BFS学习笔记
笔记·学习·算法
Ch_ty1 天前
leetcode解题思路分析(一百六十八)1452 - 1458 题
算法·leetcode·哈希算法
哼?~1 天前
算法学习--离散化
算法
AI科技星1 天前
引力编程时代:人类文明存续与升维
数据结构·人工智能·经验分享·算法·计算机视觉
Blossom.1181 天前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
轻微的风格艾丝凡1 天前
卷积的直观理解
人工智能·深度学习·神经网络·算法·计算机视觉·matlab·cnn
田梓燊1 天前
红黑树分析 1
算法