Cod sursa(job #2083188)

Utilizator calin9819Costea Calin calin9819 Data 7 decembrie 2017 10:36:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

int t[100001], nivel[100001];

void reuniune(int x, int y) {
    if (nivel[x] > nivel[y])
        nivel[x] += nivel[y],
        t[y] = x;
    else
        nivel[y] += nivel[x],
        t[x] = y;
}

int tata(int x) {
    if(x != t[x])
        t[x] = tata(t[x]);
    return t[x];
}

int main()
{
    int N, M;
    f >> N >> M;
    for (int i = 1; i <= N; i++) {
        t[i] = i;
        nivel[i] = 1;
    }
    for (int i = 1; i <= M; i++) {
        int q, x, y;
        f >> q >> x >> y;
        if (q == 1) {
            reuniune(tata(x), tata(y));
        } else {
            if (tata(x) == tata(y))
                g << "DA\n";
            else
                g << "NU\n";
        }
    }
    return 0;
}