P1551 亲戚
并查集还是不熟,还得练
#include<iostream>
#include<set>
#include<map>
#include<algorithm>
#include<vector>
#define int long long
const int N = 1e6;
using namespace std;
char* p1, * p2, buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{
int x = 0, f = 1;
char ch = nc();
while (ch < 48 || ch>57)
{
if (ch == '-')
f = -1;
ch = nc();
}
while (ch >= 48 && ch <= 57)
x = x * 10 + ch - 48, ch = nc();
return x * f;
}
int a[N];
int ans = 0;
int n, c;
int f[N];
int find(int x) {//查询并修改父节点
if (f[x] == x)return x;
f[x] = find(f[x]);
return f[x];
}
void unionn(int x, int y) {
f[y] = x;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m, p;
cin >> n >> m>>p;
for (int i = 1; i <= n; i++)f[i] = i;
for (int i = 1; i <= m; i++) {
int p1, p2;
cin >> p1 >> p2;
int r1 = find(p1);
int r2 = find(p2);
if (r1 != r2)unionn(r1, r2);//合并两个点
}
for (int i = 1; i <= p; i++) {
int p1, p2;
cin >> p1 >> p2;
if (find(p1) == find(p2))cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
分类:
并查集
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下