专栏文章
P1551 亲戚 题解
P1551题解参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @minek3ev
- 此快照首次捕获于
- 2025/12/02 01:07 3 个月前
- 此快照最后确认于
- 2025/12/02 01:07 3 个月前
P1551 亲戚 题解
上代码
CPP#include <iostream>//并查集
using namespace std;
const int N = 5010;
int root[N],n,m,p;
void init(int i){ root[i] = i; }//先初始化 自己指向自己
int find(int x){//找x的root
if(root[x] == x) return x;//x是root
return root[x] = find(root[x]);//路径压缩
}
void merge(int x,int y){//合并两棵树
int rootx = find(x);
int rooty = find(y);
if(rootx != rooty) {
if(rootx >= rooty) root[rootx] = rooty;
else root[rooty] = rootx;
}
}
int main(){
cin >> n >> m >> p;
for(int i = 1;i <= n;i++) init(i);
for(int i = 1;i <= m;i++){
int x,y; cin >> x >> y;
merge(x,y);
}
while(p--){
int x,y; cin >> x >> y;
if(find(x) == find(y)) cout << "Yes\n";
else cout << "No\n";
}
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...