Cod sursa(job #1674926)

Utilizator dex4Darjan Catalin dex4 Data 4 aprilie 2016 22:46:28
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;

int n, m, padre[nmax], depth[nmax];

void set_value(){
    for(int i=1; i<=n; i++){
        padre[i] = i;
        depth[i] = 1;
    }
}

int parent(int x){
    while(x != padre[x])
        x = padre[x];
   return x;
}

void unite(int x, int y){
    x = parent(x);
    y = parent(y);
    if(depth[x] > depth[y])
        padre[y] = x;
    else
        if(depth[x] < depth[y])
            padre[x] = y;
        else{
            padre[y] = x;
            depth[x]++;
        }
}

void solve(){
    int p, x, y;
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    f >> n >> m;
    set_value();
    for(int i=1; i<=m; i++){
        f >> p >> x >> y;
        if(p == 1){
            unite(x, y);
        }
        if(p == 2){
            g << (parent(x) == parent(y) ? "DA\n" : "NU\n");
        }
    }
}

int main()
{
    solve();
    return 0;
}