Cod sursa(job #1127750)

Utilizator muresan_bogdanMuresan Bogdan muresan_bogdan Data 27 februarie 2014 13:41:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include<iostream>
#include<fstream>
using namespace std;

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

int  rang[100001],tata[100001], n, m, i, c, x, y;

int top(int a) {
    int rad = a, aux;
    while(tata[rad] != rad) {
        rad = tata[rad];
    }
    while(tata[a] != rad) {
        aux = tata[a];
        tata[a] = rad;
        a = aux;
    }
    return rad;
}

void unite(int a, int b) {
    if(rang[a] > rang[b]) {
        tata[b] = a;
    }
    else{
        if(rang[a] == rang[b]) {
            rang[b]++;
        }
        tata[a] = b;
    }
}

int main() {
    fin >> n >> m;
    for(i = 1; i < n; i++) {
        tata[i] = i;
        rang[i] = 1;
    }
    for(i = 0; i < m; i++) {
        fin >> c >> x >> y;
        if(c == 1) {
            unite(top(x), top(y));
        }
        if(c == 2) {
            if(top(x) == top(y)) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }
}