思路:
(1)有合并,与查询是否同集合,查询集合中点的数量三种操作,于是考虑用并查集存储集合,用cnt【】存储集合编号里点的数量。
(2)流程:
- 预处理,切分为n个集合,每个集合祖宗处记录集合内点数量为1;
- 合并:a祖宗认b祖宗为祖宗,b祖宗加上a祖宗处记录的数量;查询是否同一集合:判断祖宗是否相同,相同则是同集合,否则不是;查询所在集合点的数量:查询祖宗处存的集合内点数即可。
代码:
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int p[N],cnt[N];
int find(int x)
{
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
int main()
{
int n,m;
cin >> n >> m;
for(int i = 1;i <= n;i ++)
{
p[i] = i;
cnt[i] = 1;
}
while(m --)
{
string op;
int a,b;
cin >> op >> a ;
if(op == "C")
{
cin >> b;
if(find(a) != find(b)) cnt[find(b)] += cnt[find(a)];
p[find(a)] = find(b);
}
else if(op == "Q1")
{
cin >> b;
if(find(a) == find(b)) puts("Yes");
else puts("No");
}
else
{
cout << cnt[find(a)] << endl;
}
}
return 0;
}