Cod sursa(job #2721050)

Utilizator PatrickCplusplusPatrick Kristian Ondreovici PatrickCplusplus Data 11 martie 2021 15:27:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
using namespace std;

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

const int nmax = 100005;
int n, m, tata[nmax], r[nmax];

int getParent(int x){
    int nod = x;
    while (tata[nod] != nod){
        nod = tata[nod];
    }
    while (tata[x] != x){
        int aux = tata[x];
        tata[x] = nod;
        x = aux;
    }
    return nod;
}

void Union(int x, int y){
    int pX = getParent(x);
    int pY = getParent(y);
    if (pX == pY){
        return;
    }
    if (r[pX] < r[pY]){
        tata[pX] = pY;
    }
    else{
        tata[pY] = pX;
    }
}

int main(){
    fin >> n >> m;
    for (int i = 1; i <= n; ++i){
        tata[i] = i;
    }
    while (m--){
        int tip, x, y;
        fin >> tip >> x >> y;
        if (tip == 1){
            Union(x, y);
        }
        else{
            if (getParent(x) == getParent(y)){
                fout << "DA\n";
            }
            else{
                fout << "NU\n";
            }
        }
    }
    fin.close();
    fout.close();
    return 0;
}