AcWing 837. 连通块中点的数量
原题链接
简单
作者:
YMYS
,
2025-03-13 22:25:42
·河南
,
所有人可见
,
阅读 5
/*
* @Author: YMYS
* @Date: 2025-03-12 22:08:31
* @LastEditTime: 2025-03-13 22:23:07
* @FilePath: \VScode-C&C++-Coding\蓝桥杯真题\官网题库\xxx.cpp
* @URL:https://www.acwing.com/problem/content/description/839/
* @Description: 837. 连通块中点的数量
*
* 并查集 + 模拟
*
*/
#include<bits/stdc++.h>
#define int long long
#define err cout << "error" << endl
using namespace std;
const int N = 1e5 + 10;
// int T;
// void solve(){
// }
int n, m;
int p[N];//p[i]表示i的父亲节点
int si[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
signed main()
{
#ifdef ABC
freopen("D:/daily_Coding/VScode-C&C++-Coding/in.in", "r", stdin);
freopen("D:/daily_Coding/VScode-C&C++-Coding/out.out", "w", stdout);
#endif
std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
// cin>>T;
// while(T--){
// solve();
// }
cin >> n >> m;
//初始化
for (int i = 1; i <= n; i++) {
p[i] = i;
si[i] = 1;
}
while (m--) {
string c;
cin >> c;
if (c == "C") {
int a, b;
cin >> a >> b;
if (find(a) == find(b)) continue;
//先把树上的点都加上去
si[find(b)] += si[find(a)];
//再把两颗树合并
p[find(a)] = find(b);
// p[find(b)] = find(a);这行代码写不写都可以AC,因为是无向图
//错误写法!不能先合并再拼接
// si[find(b)] += si[find(a)];
}
else if (c == "Q1") {
int a, b;
cin >> a >> b;
if (find(p[a]) == find(p[b]) || find(p[b]) == find(p[a])) cout << "Yes" << endl;
else cout << "No" << endl;
}
else if(c == "Q2"){
int a;
cin >> a;
//注意我们不可以在这里遍历1~n,那样的话时间复杂度就是O(n^2)了
//我们需要想办法新建一个数组去记录点的数量,具体怎么计算,我们就需要去其他地方蹭循环了
cout << si[find(a)] << endl;
}
}
return 0;
}