AcWing 836. 合并集合

Posted MangataTS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AcWing 836. 合并集合相关的知识,希望对你有一定的参考价值。

题目连接

https://www.acwing.com/problem/content/838/

思路

并查集模板题

  • 当操作是合并时,先判断两者是否在一个集合,然后合并(其实不用判断也可以,反正都是一个集合的)
  • 当操作是查询时,我们直接判断两者是否在一个集合里面就好了

代码

#include<bits/stdc++.h>
using namespace std;
//----------------自定义部分----------------
#define ll long long
#define mod 1000000009
#define endl "\\n"
#define PII pair<int,int>

int dx[4]=0,-1,0,1,dy[4]=-1,0,1,0;

ll ksm(ll a,ll b) 
	ll ans = 1;
	for(;b;b>>=1LL) 
		if(b & 1) ans = ans * a % mod;
		a = a * a % mod;
	
	return ans;


ll lowbit(ll x)return -x & x;

const int N = 2e6+10;
//----------------自定义部分----------------
int n,m,q,a[N];

int fa[N];
void init()
	for(int i = 1;i <= n; ++i) fa[i] = i;

int find(int x)
	int t = x;
	while(t != fa[t]) t = fa[t];
	while(x != fa[x]) 
		int temp = fa[x];
		fa[x] = t;
		x = temp;
	
	return x;


int main()

	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout.tie(nullptr);
	cin>>n>>m;
	init();
	char op;
	int u,v;
	for(int i = 0;i < m; ++i) 
		cin>>op>>u>>v;
		u = find(u);
		v = find(v);
		if(op == 'M')
			if(u != v) fa[v] = u;
		else
			puts(u==v?"Yes":"No");
		
		
	
	return 0;

以上是关于AcWing 836. 合并集合的主要内容,如果未能解决你的问题,请参考以下文章

836. 合并集合(并查集)

并查集 C++版本 Python版本

AcWing 837. 连通块中点的数量

UVa 836 - Largest Submatrix

AcWing 803. 区间合并

AcWing 803. 区间合并