Cod sursa(job #1300258)

Utilizator somuBanil Ardej somu Data 24 decembrie 2014 11:30:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>
#define nmax 100005
using namespace std;

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

int n, m;
int R[nmax], NR[nmax];

void initialize() {
    int i;
    for (i = 1; i <= n; i++) {
        R[i] = i;
        NR[i] = i;
    }
}

int root(int x) {
    if (R[x] == x)
        return x;
    return root(R[x]);
}

void join(int x, int y) {
    int rx, ry;
    rx = root(x);
    ry = root(y);
    if (NR[rx] >= NR[ry]) {
        NR[rx] += NR[ry];
        R[ry] = rx;
    } else {
        NR[ry] += NR[rx];
        R[rx] = ry;
    }
}

void solve() {
    int i, op, x, y;
    fin >> n >> m;
    initialize();
    for (i = 1; i <= m; i++) {
        fin >> op >> x >> y;
        if (op == 1)
            join(x, y);
        else {
            if (root(x) == root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
}

int main() {
    solve();
    fin.close();
    fout.close();
    return 0;
}