Cod sursa(job #1857179)

Utilizator GeorginskyGeorge Georginsky Data 25 ianuarie 2017 21:39:59
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 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;
        if(op==1)merge_sets(find_set(a), find_set(b));
        else cout<<((find_set(a)==find_set(b))?"DA":"NU")<<"\n";
    }
    return 0;
}