Cod sursa(job #2082247)

Utilizator alittlezzCazaciuc Valentin alittlezz Data 5 decembrie 2017 21:16:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;
#define ll long long

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int N = 1e5 + 5;
int p[N], dp[N];

int getP(int node){
    if(node != p[node]){
        p[node] = getP(p[node]);
    }
    return p[node];
}

void unite(int x, int y){
    x = getP(x);
    y = getP(y);
    if(dp[x] > dp[y]){
        dp[y] += dp[x];
        p[y] = x;
    }else{
        dp[x] += dp[y];
        p[x] = y;
    }
}

bool areUnited(int x, int y){
    x = getP(x);
    y = getP(y);
    return x == y;
}

int main(){
    int n, q;
    fin >> n >> q;
    for(int i = 1;i <= n;i++){
        p[i] = i;
        dp[i] = 1;
    }
    for(int i = 1;i <= q;i++){
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1){
            unite(x, y);
        }else{
            fout << (areUnited(x, y) ? "DA" : "NU") << '\n';
        }
    }
    return 0;
}