[3367] Luo Gu template disjoint-set

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:  Copy
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:  Copy
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.

 

Solution: do not need explanations Ahem cough, and relatives that questions like ah.

//#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
int n,m,p,a,b,s1,s2,fa[10005],ans;
int find(int x){
   if(fa[x]==x) return x;
   return fa[x]=find(fa[x]);
}
int main(){
    freopen("3367.in","r",stdin);
    freopen("3367.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++) fa[i]=i;
    while(m--){
        scanf("%d %d %d",&p,&a,&b);
        if(p==1){
            s1=find(a); s2=find(b);
            if(s1!=s2) fa[s2]=s1;
        }
        else{
             if(find(a)==find(b))
                printf("Y\n");
             else printf("N\n");
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/wuhu-JJJ/p/11129355.html