数据结构——并查集

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;
}
相关推荐
爱喝热水的呀哈喽28 分钟前
11题目汇总
算法
三斗米1 小时前
Transformer入门:一文读懂《Attention Is All You Need》
算法·架构
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——链表相加(二)
数据结构·链表·牛客·结构与算法
报错小能手1 小时前
数据结构 可扩展哈希
数据结构·哈希算法·散列表
Swift社区1 小时前
LeetCode 458 - 可怜的小猪
算法·leetcode·职场和发展
AI科技星1 小时前
宇宙的像素:真空中一点如何编码无限星光
数据结构·人工智能·算法·机器学习·重构
程芯带你刷C语言简单算法题1 小时前
Day37~求组合数
c语言·开发语言·学习·算法·c
程序员-周李斌1 小时前
transmittable-thread-local[线程池跨线程值传递]
java·开发语言·算法·散列表
Flash.kkl1 小时前
优先算法专题十七——多源BFS
算法·宽度优先
Yzzz-F1 小时前
牛客小白月赛 D[差分] E [暴力枚举] F[] g[二阶差分]
算法