多学习。

【并查集】AcWing837. 连通块中点的数量

AcWing837. 连通块中点的数量

题解

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 1e5 + 10;

int p[N], cnt[N], n, m, x, y;

int find(int x)
{
    if(p[x] != x) return p[x] = find(p[x]);
    return x;
}

int main()
{
    string s;
    scanf("%d%d", &n, &m);
    
    for(int i = 1; i <= n; ++i) p[i] = i, cnt[i] = 1;
    
    while(m -- )
    {
        cin >> s;
        scanf("%d",&x);
        if(s == "C")
        {
            scanf("%d",&y);
            int a = find(x), b = find(y);  //注意:x,y可能相等
            if(a != b) cnt[b] += cnt[a], p[a] = b;
        }
        else if(s == "Q1") 
            scanf("%d",&y),printf("%s\n",find(x) == find(y) ? "Yes" : "No");
        else printf("%d\n",cnt[find(x)]);
    }
    
    return 0;
}
posted @ 2022-05-18 21:29  czyaaa  阅读(38)  评论(0)    收藏  举报