Cod sursa(job #1965608)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 14 aprilie 2017 15:08:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>

using namespace std;

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

const int nmax = 100005;
int t, x, y, X, Y, n, m, i;
int tt[nmax], gr[nmax];

int update(int x) {
    int r=x, y;
    while (tt[r]!=r) r = tt[r];
    while (tt[x]!=x) {
        y = tt[x];
        tt[x] = r;
        x = y;
    }
    return r;
}

void uneste(int x, int y) {
    if (gr[x] > gr[y]) tt[y]=x;
    else tt[x]=y;
    if (gr[x]==gr[y])gr[y]++;
}

int main() {
    f >> n >> m;
    for (i = 1; i <= n; i++)
        tt[i]=i, gr[i]=1;
    for (i = 1; i <= m; i++) {
        f >> t >> x >> y;
        X = update(x), Y = update(y);
        if (t==2)
            g << (X!=Y?"NU\n":"DA\n");
        else if (X!=Y) uneste(X, Y);
    }
    return 0;
}