Cod sursa(job #2066391)

Utilizator Teodor.mTeodor Marchitan Teodor.m Data 14 noiembrie 2017 22:56:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;

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

const int Nmax = 1e5 + 10;

int tata[Nmax], nivel[Nmax];

void cod_1(int x, int y) //unesc multimea in care se afla x cu multimea in care se afla y
{
    if(nivel[x] < nivel[y]) // arborele cu nivelul mai mic in unesc de cel cu nivelul mai mare
        tata[x] = y;
    else
        tata[y] = x;

    if(nivel[x] == nivel[y]) { // daca nivelul este acelasi pentru cei doi arbori atunci cresc oricare din cele doue nivele
        tata[y] = x;
        nivel[x]++;
    }
}

int cod_2(int x)
{
    int root = x;

    while(tata[root] != root) root = tata[root]; // am determinat radacina nodului x

    while(tata[x] != root) { // am creat o legatura de la fiecare nod prin care trece x la radacina acestuia
        int aux = tata[x];
        tata[x] = root;
        x = aux;
    }

    return root;
}

int main()
{
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; ++i) {
        tata[i] = i;
        nivel[i] = 1;
    }

    for(int i = 1; i <= m; i++) {
        int cod, x, y;
        fin >>cod >> x >> y;
        if(cod == 1) {
            cod_1(cod_2(x), cod_2(y));
        }

        if(cod == 2) {
            if(cod_2(x) == cod_2(y))
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';
        }
    }
    return 0;
}