并查集模板题:合并集合

#include 
#include 
#include 

using namespace std;

const int N = 1e5 + 10;
int p[N];

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

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i ++ )
        p[i] = i;
    
    while (m -- )
    {
        char op;
        int a, b;
        cin >> op;
        
        if (op == 'M')
        {
            cin >> a >> b;
            int pa = find(a), pb = find(b);
            if (pa != pb)
                p[pa] = pb;
        }
        else {
            cin >> a >> b;
            int pa = find(a), pb = find(b);
            if (pa != pb)
                puts("No");
            else
                puts("Yes");
        }
    }
    
    return 0;
}

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