acwing837. 连通块中点的数量(并查集)

在这里插入图片描述

  1. 并查集的有的神奇妙用是把一个问题我们倒过来考虑的时候,比如题目让我们分割一个数组或集合,我们考虑这个的逆过程,我们考虑用并查集考虑合并。

代码

#include <bits/stdc++.h>
using namespace std;
#define db  double
#define ll  long long
#define Pir pair<int, int>
#define fi  first
#define se  second
#define pb  push_back
#define m_p make_pair
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3f
/*==========ACMer===========*/
const int N = 1e5 + 10;
int fa[N], cnt[N];
int find(int x)
{
    
    
    if (fa[x] == x) return x;
    return fa[x] = find(fa[x]);
}


int main()
{
    
    
    int n, m;
    scanf("%d %d ", &n, &m);
    for (int i = 1; i <= n; i ++) fa[i] = i, cnt[i] = 1;
    string op; int x, y;
    while (m --)
    {
    
    
        cin >> op;
        if(op == "C")
        {
    
    
            cin >> x >> y;
            int fx = find(x);
            int fy = find(y);
            if (fx != fy)
            {
    
    
                fa[fx] = fy;
                cnt[fy] += cnt[fx];
            }
        }
        else if (op == "Q1")
        {
    
    
            cin >> x >> y;
            int fx = find(x);
            int fy = find(y);
            if (fx == fy)
                printf("Yes\n");
            else
                printf("No\n");
        }
        else if (op == "Q2")
        {
    
    
            cin >> x;
            int fx = find(x);
            printf("%d\n", cnt[fx]);
        }

    }

    return 0;
}




Guess you like

Origin blog.csdn.net/qq_34261446/article/details/121494192