数据结构——并查集

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;
}
相关推荐
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号2 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区3 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9854 小时前
BCH码编译码仿真与误码率性能分析
算法
小白不想白a4 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
剪一朵云爱着4 小时前
力扣2080. 区间内查询数字的频率
算法·leetcode
落日漫游4 小时前
数据结构笔试核心考点
java·开发语言·算法
Doro再努力4 小时前
数据结构04:力扣顺序表3道例题解题思路与代码实现
c语言·数据结构
HY小海5 小时前
【C++】AVL树实现
开发语言·数据结构·c++
workflower5 小时前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程