Cod sursa(job #1789975)

Utilizator HuskyezTarnu Cristian Huskyez Data 27 octombrie 2016 17:43:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>

#define infile "disjoint.in"
#define outfile "disjoint.out"

using namespace std;

ifstream in(infile);
ofstream out(outfile);

int n, m;
short int op;
int x, y;
int roots[100005];
int height[100005];

int find_root(int node)
{
    int root, x;
    for(x=node; x!=roots[x]; x = roots[x]);

    root = x;

    for(x=node; x!=roots[x]; x = roots[x]){
        roots[x] = root;
    }
    return root;
}

void combine(int x, int y)
{
    int node1 = find_root(x);
    int node2 = find_root(y);

    if(height[node1] > height[node2]){
        roots[node2] = node1;
        return;
    }
    if(height[node2] > height[node1]){
        roots[node1] = node2;
        return;
    }
    if(height[node2] == height[node1]){
        roots[node2] = node1;
        height[node1]++;
    }
    return;
}

int main()
{
    in >> n >> m;
    for(int i=1; i<=n; i++){
        roots[i] = i;
    }
    for(int i=0; i<m; i++){
        in >> op;
        if(op == 1){
            in >> x >> y;
            combine(x, y);
        }else{
            in >> x >> y;
            find_root(x) == find_root(y) ? out << "DA" << '\n' : out << "NU" << '\n';
        }
    }

    return 0;
}