Cod sursa(job #1857176)

Utilizator GeorginskyGeorge Georginsky Data 25 ianuarie 2017 21:31:53
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <iostream>
#include <cstdio>
#define N 100005
using namespace std;
int n, m, p[N], r[N];
int find_set(int x){
    if(x!=p[x])p[x]=find_set(p[x]);
    return p[x];
}

void merge_sets(int x, int y){
    if(r[x]>r[y])p[y]=x;
    else p[x]=y;
    if(r[x]==r[y])r[y]++;
}

int main(){
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    cin>>n>>m;
    int op, a, b, set1, set2;
    for(int i=1; i<=n; i++)p[i]=i,r[i]=1;
    for(int i=1; i<=m; i++){
        cin>>op>>a>>b;
        set1=find_set(a);
        set2=find_set(b);
        if(op==1)merge_sets(set1, set2);
        else cout<<((find_set(set1)==find_set(set2))?"DA":"NU")<<"\n";
    }
    return 0;
}