可以将连通块看成集合,合并连通块可以看成将集合合并,但是要注意存储连通块中的点数
#include <iostream> #include <cstring> #include <algorithm> using namespace std; const int N = 100010; int n, m; int p[N], cnt[N]; int find(int x) //查询加路径压缩 { if(p[x] != x) p[x] = find(p[x]); return p[x]; } int main() { 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; if(op == "C") { cin>>a>>b; a = find(a), b = find(b); if(a != b) { p[a] = b; cnt[b] += cnt[a]; } } else if(op == "Q1") { cin>>a>>b; if(find(a) == find(b)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } else { cin>>a; cout<<cnt[find(a)]<<endl; } } return 0; }