数据结构——并查集

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;
}
相关推荐
H_z___1 天前
Codeforces Global Round 31 (Div. 1 + Div. 2) A ~ E
数据结构·算法
Dylan的码园1 天前
队列与queue
java·数据结构·链表
小龙报1 天前
【算法通关指南:算法基础篇 】双指针专题:1.唯一的雪花 2.逛画展 3.字符串 4.丢手绢
c语言·数据结构·c++·人工智能·深度学习·算法·信息与通信
superman超哥1 天前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q1 天前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
阿昭L1 天前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹1 天前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
liuyao_xianhui1 天前
0~n-1中缺失的数字_优选算法(二分查找)
算法
hmbbcsm1 天前
python做题小记(八)
开发语言·c++·算法
机器学习之心1 天前
基于Stacking集成学习算法的数据回归预测(4种基学习器PLS、SVM、BP、RF,元学习器LSBoost)MATLAB代码
算法·回归·集成学习·stacking集成学习