算法基础课:合并集合

#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int s[N], p[N];
int find(int x)
{
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}
void merge(int a, int b)
{
    int x = find(a), y = find(b);
    p[x] = y;
}
void query(int a, int b)
{
    if (find(a) == find(b))
    puts("Yes");
    else
    puts("No");
}
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i ++)
    {
        p[i] = i;
    }
    while (m --)
    {
        string op;
        int a, b;
        cin >> op >> a >> b;
        if (op == "M")
        {
            merge(a, b);
        }
        if (op == "Q")
        {
            query(a, b);
        }
    }
}
上一篇:哈希表开放寻址法


下一篇:左递归文法在Parser Combinator中的解决办法(FParserc)