有n个二维平面上的点和距离d,将它们分成k组。
若两点间的距离小于等于d,则这两个点在一组;如果点A和点B在一组,点B和点C在一组,则点A和点C在一组。
算法返回每个点所在组的编号(0..k-1)
典型的并查集问题
并查集,两重循环枚举点,连起来,时间复杂度O(N^2)
关于并查集的模板:代码特别短,只写路径压缩:
p[x] 表示x的父亲节点,初始化p[x] = x
核心函数:find(x) 返回x的祖宗节点,考虑路径压缩以后的写法:
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
如何判断x和y是否在同一个集合中
bool isSameSet(int x, int y){
return find(x) == find(y);
}
合并两个元素
void union(int x, int y){
p[find[x]] = y;
}
836. 合并集合
Acwing 836
#include <iostream>
using namespace std;
const int N = 100010;
int p[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
bool isSameSet(int x, int y){
return find(x) == find(y);
}
void union(int x, int y){
p[find[x]] = y;
}
int main()
{
int n, m, a,b;
char op;
cin>>n>>m;
for(int i=1;i<=n;i++) p[i] = i;
for(int i=0;i<m;i++){
cin>>op>>a>>b;
if(op=='M'){
p[find(a)] = find(b);
}
if(op=='Q'){
if(find(a)==find(b)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
}