Cod sursa(job #1795379)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 2 noiembrie 2016 12:04:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5 + 1;

int n, q;
int t[NMAX], sz[NMAX];

inline int root(int x) {
    while (x != t[x])
        x = t[x];
    return x;
}

inline void unite(int x, int y) {
    int tx = root(x);
    int ty = root(y);
    if (tx == ty)
        return;
    if (sz[tx] == sz[ty])
        ++sz[tx];
    if (sz[tx] > sz[ty])
        t[ty] = tx;
    else
        t[tx] = ty;
}

int main()
{
    fin >> n >> q;
    for (int i = 1; i <= n; ++i) { // initializare
        t[i] = i; // nodul pointeaza la el insusi
        sz[i] = 1; // subarborele cu radacina i are 1 nod
    }
    for (int op, x, y; q; --q) {
        fin >> op >> x >> y;
        if (op == 1) {
            unite(x, y);
        }
        if (op == 2) {
            if (root(x) == root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}