acwing836. 合并集合(并查集)

acwing836. 合并集合(并查集)_第1张图片

思路

  1. 并查集可以判断连通块的数量,可以判断集合的大小。

代码

#include 
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];
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;
    char ch; int x, y;
    while (m --)
    {
        scanf("%c %d %d ", &ch, &x, &y);
        if (ch == 'M')
        {
            int fx = find(x);
            int fy = find(y);
            if (fx != fy)
            {
                fa[fx] = fy;
            }
        }
        else
        {
            int fx = find(x);
            int fy = find(y);
            if (fx == fy)
                printf("Yes\n");
            else
                printf("No\n");
        }
    }

    return 0;
}

你可能感兴趣的:(#,并查子集,图论,算法,java)