数据结构——并查集

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;
}
相关推荐
小林熬夜学编程15 分钟前
【MySQL】第十一弹---复合查询全攻略:多表、自连接、子查询与合并查询
android·linux·开发语言·数据库·mysql·算法
修己xj1 小时前
算法系列之排序算法-堆排序
数据结构·算法·排序算法
Serendipity-Solitude1 小时前
物联网概念
物联网·算法
补三补四1 小时前
因子有效性的审判使者——回测分析【量化实践】
大数据·人工智能·算法·金融·数据分析
憧憬从前2 小时前
头歌实验---C/C++程序设计:实验2:顺序结构程序设计
c语言·c++·算法
mvufi2 小时前
day22 第七章 回溯算法part01
算法
大锦终2 小时前
常见排序算法
c语言·算法·排序算法
guihong0042 小时前
分布式系统中的关键技术解析:幂等性、负载均衡、限流算法及其实现
运维·算法·负载均衡
Reese_Cool2 小时前
【洛谷贪心算法】P1106删数问题
c++·算法·贪心算法·蓝桥杯
迷茫小玄森2 小时前
逻辑回归-乳腺癌肿瘤预测
人工智能·算法·机器学习·回归·逻辑回归·sklearn