Cod sursa(job #2060482)

Utilizator zeboftwAlex Mocanu zeboftw Data 8 noiembrie 2017 12:10:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 100005;

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

int parent[NMAX], ranking[NMAX];

int find_root (int x) {
    if (parent[x] != x)
        parent[x] = find_root(parent[x]);
    return parent[x];
}

int unite (int x, int y) {
    int xRoot = find_root(x);
    int yRoot = find_root(y);

    //cout << "xRoot = " << xRoot << " & yRoot = " << yRoot << '\n';

    if(ranking[xRoot] > ranking[yRoot])
        parent[yRoot] = xRoot;
    else if (ranking[xRoot] < ranking[yRoot])
        parent[xRoot] = yRoot;
    else {
        parent[yRoot] = x;
        ranking[xRoot]++;
    }
}

int main()
{
    int n, m;

    fin >> n >> m;

    for (int i=1; i <= n; i++) parent[i] = i;

    for (int i=1; i <= m; i++) {
        int cod, x, y;
        fin >> cod >> x >> y;
        if (cod == 1) {
            unite(x,y);
        }
        else {
            if (find_root(x) == find_root(y)) fout << "DA\n";
            else fout << "NU\n";
        }
    }

    return 0;
}