Disjoint-set: Number of blocks communication midpoint

Title link: https: //www.acwing.com/problem/content/839/
meaning of the questions : Given a n points (numbered 1 ~ n) undirected graph, the initial drawing no edges.
M perform operations now, there are three operations:
. 1, "ab & C", even one side, a and b may be equal between points a and b;
2, "ab & Ql", interrogation points a and b are in communication with a block, a and b may be equal;
. 3, "a Q2", where the communication with a number of interrogation points the midpoint of blocks;
data range
1≤n, m≤105
input sample:
. 5. 5
C 2. 1
1 2 Q1
Q2 1
C 5 2
Q2 5
sample output:
Yes
2
3
ideas : in fact, the title and the title on a blog similar, but more a process of seeking the number of nodes, as long as the root node size [] interest on it.
Code:

#include<iostream>
using namespace std;
const int N = 1e5 + 5;
int n, m;
int p[N], size[N];
//返回x的根节点 + 路径压缩
int find(int x)
{
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}
int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i ++ ){
        p[i] = i;
        size[i] = 1;
    }
    while(m -- ){
        char op[5];
        int a, b;
        cin >> op;
        if(op[0] == 'C'){
            cin >> a >> b;
            if(find(a) == find(b)) continue;
            size[find(b)] += size[find(a)];
            p[find(a)] = find(b);
        }
        else if(op[1] == '1'){
            cin >> a >> b;
            if(find(a) == find(b)) cout << "Yes" << endl;
            else cout << "No" << endl;
        }
        else{
            cin >> a;
            cout << size[find(a)] << endl;
        }
    }
    return 0;
}


Published 61 original articles · won praise 0 · Views 932

Guess you like

Origin blog.csdn.net/Satur9/article/details/104088755