Cod sursa(job #1333162)

Utilizator tudi98Cozma Tudor tudi98 Data 2 februarie 2015 20:54:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
using namespace std;

int P[100005];
int h[100005];

int root(int x){
    if(P[x] != x) P[x] = root(P[x]);
    return P[x];
}

void unite(int x,int y){
    int Rx = root(x);
    int Ry = root(y);
    if(h[Rx] > h[Ry]){
        h[Rx] += h[Ry];
        P[Ry] = Rx;
    }
    else{
        h[Ry] += h[Rx];
        P[Rx] = Ry;
    }
}

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

    int n,m;

    fin >> n >> m;

    for(int i = 1; i <= n; i++){
        P[i] = i;
        h[i] = 1;
    }

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