Cod sursa(job #1921953)

Utilizator RaTonAndrei Raton RaTon Data 10 martie 2017 15:28:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int N, V[100001];
int RG[100001];
int stramos(int x){
    if(V[x] == x)
        return x;
    V[x] = stramos(V[x]);
    return V[x];
}

int main()
{
    int m, i, v, x, y, nx, ny;
    f >> N >> m;
    for(i = 1; i <= N; i++){
        V[i] = i;
        RG[i] = 1;
    }
    for(i = 1; i <= m; i++){
        f >> v >> x >> y;
        if(v == 1){
            nx = stramos(x);
            ny = stramos(y);
            if(RG[nx] < RG[ny]){//de nodul cu rang mai mare leg nodul cu rang mai mic
                V[nx] = V[ny];
                RG[nx] = RG[ny];
            }
            else if( RG[nx] > RG[ny] ){
                V[ny] = V[nx];
                RG[ny] = RG[nx];
            }
            else{
                V[nx] = V[ny];
                RG[nx]++;
                RG[ny]++;
            }
        }
        else{
            if(stramos(x) == stramos(y))
                g << "DA";
            else
                g << "NU";
            g << '\n';
        }
    }
    return 0;
}