连通块中点的数量

# 题意

给定一个包含n个点(编号为1~n)的无向图,初始时图中没有边。

现在要进行m个操作,操作共有三种:

1)“C a b”,在点a和点b之间连一条边,a和b可能相等;

2)“Q1 a b”,询问点a和点b是否在同一个连通块中,a和b可能相等;

3)“Q2 a”,询问点a所在连通块中点的数量;

# 题解

连边就是集合的合并,维护集合大小的并查集,连通块数量即size

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e5+10;
 4 int fa[N];
 5 int sz[N];
 6 int n,m;
 7 int find(int x){
 8     if(fa[x]!=x) fa[x]=find(fa[x]);
 9     return fa[x];
10 }
11 void merge(int a,int b){
12     if(find(a)==find(b))
13         return;
14     else{
15         sz[find(b)]+=sz[find(a)];
16         fa[find(a)]=find(b);
17     }
18 }
19 int main(){
20     cin>>n>>m;
21     for(int i=1;i<=n;i++){
22         fa[i]=i;
23         sz[i]=1;
24     }
25 
26     while(m--){
27         char op[5];
28         int a,b;
29         cin>>op;
30         if(op[0]=='C'){
31             cin>>a>>b;
32             merge(a,b);
33         }
34         else if(op[1]=='1'){
35             cin>>a>>b;
36             if(find(a)==find(b))
37                 cout<<"Yes"<<endl;
38             else cout<<"No"<<endl;
39         }
40         else {
41             cin>>a;
42             cout<<sz[find(a)]<<endl;
43         }
44     }
45 }

猜你喜欢

转载自www.cnblogs.com/hhyx/p/12439109.html