【模板】并查集

并查集

查找某个点在哪个集合, 两个集合的合并,比如看两个城市是否相连就看是否在同一集合

刚开始每个点的都是一个单独的集合,所以初始化的时候指向自己 每当添加(合并)一个点 就让合并的点指向自己

fa是集合数组 用来记录 每个点所在的是哪一个集合,就像多叉树

1
2
3
void unionset(int x,int y){//x集合并入y集合
    fa[find(x)] = find(y); //
}

但这样合并会出现如下

1并入2 1-2

2并入3 1-2-3 … 退化为链表 向上查找就变慢

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
int fa[1000010];//记录每个点所属的集合
int find(int x){
    //最开始的结点都是指向自己的
	if(x == fa[x]) return x;
    //每次向上查找所属哪个集合 找到了就更新一下
	return fa[x] = find(fa[x]);
}

//x并入y
void unionset(int x, int y){
	fa[find(x)] = find(y);
}

//小集合并入大集合会比较好  一般用不上
vector<int> sz(1000010,1);//记录数量集合大小
void unionset2(int x, int y){
	x = find(x) , y = find(y);
	if(x == y) return ;
	if(sz[x] > sz[y]) swap(x,y);
	fa[x] = y;
	sz[y]+=sz[x];
}

https://www.luogu.com.cn/problem/P3367

答案

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <bits/stdc++.h>
using namespace std;

#define ms(s) memset(s, 0, sizeof(s))
#define prDouble(x) std::cout << fixed << setprecision(10) << x
#define rep(i,a,n) for(int i=a;i<n;++i)
#define per(i,a,n) for(int i=n-1;i>=a;--i)
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define sd second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef basic_string<int> BI;
typedef std::pair<int,int> PII;
typedef long long ll;
typedef unsigned long long ull;

const int inf = 0x3f3f3f3f;
const ll mod = 1000000007;

mt19937 mrand(random_device{}());
int rnd(int x){return mrand() %x;}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}

void solve(){
    
}
int fa[1000010];
int find(int x){
	if(x == fa[x]) return x;
	return fa[x] = find(fa[x]);//路径压缩
}
vector<int> sz(1000010,1);
void unionset(int x, int y){
	x = find(x) , y = find(y);
	if(x == y) return ;
	if(sz[x] > sz[y]) swap(x,y);
	fa[x] = y;
	sz[y]+=sz[x];
}
// void unionset(int x, int y){
// 	if(x == y) return ;
// 	fa[find(x)] = find(y);
// }
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

	int n , m;
	std::cin>>n>>m;
	for(int i = 1;i<=n;++i) fa[i] = i;
	while(m--){
		int z , x , y;
		std::cin>>z>>x>>y;
		if(z == 1) unionset(x,y);
		else{
			std::cout<<(find(x) == find(y) ? "Y" : "N")<<"\n";
		}
	}
	return 0;
}

Built with Hugo
主题 StackJimmy 设计
本博客已风雨交加的运行了 小时 分钟
共发表 28 篇文章 · 总计 25.44 k 字