Luo Gu P3367 disjoint-set template [Title]

Title Description

As stated, there is now a disjoint-set, you need to complete the merge and query operations.

Input and output formats

Input formats:

 

The first line contains two integers N, M, N represents a total of M elements and operations.

Next M rows, each row containing three integers Zi, Xi, Yi

When Zi = 1, the combined set of Xi and Yi where

When Zi = 2, the output Xi and Yi are in the same set, is if the Y output; otherwise it outputs N

 

Output formats:

 

As above, the operation for each of the Zi = 2, has output line, each row contains a capital letter, or Y is N

 

Sample input and output

Input Sample # 1: 
4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4
Output Sample # 1: 
N 
Y 
N 
Y

Explanation

Constraints of time: 1000ms, 128M

Data Scale:

For 30% of the data, N <= 10, M <= 20;

For 70% of the data, N <= 100, M <= 1000;

To 100% of the data, N <= 10000, M <= 200000.

 

note:

And check collection and when to merge disjoint-set "root."

Note the use of recursive compression path.

 

 

The following AC Code:  645ms,  788KB

#include <iostream>
using namespace std;

const int maxn = 10001;
int N;

int p[maxn];

int ffind(int x)
{
    return p[x] == x? x : p[x] = ffind(p[x]);
}

void init(int n)
{
    for(int i = 1; i <= n ;i++)
        p[i] = i;

}

void uunion(int u, int v)
{
    p[ffind(u)] = ffind(v);
}


int main()
{

    cin >> N;
    int T;
    cin >> T;
    init(N);
    int cmd;
    int u,v;
    while(T--)
    {
        cin >> cmd;
        cin >> u >> v;
        if(cmd == 1)
        {
            uunion(u,v);
        }
        else if(cmd == 2)
        {
            int x = ffind(u);
            int y = ffind(v);
            if(x == y) cout << "Y" << endl;
            else cout << "N" << endl;

        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/YY666/p/11221674.html