Cod sursa(job #2066603)

Utilizator serban24Popovici Serban-Florin serban24 Data 15 noiembrie 2017 10:28:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define NMAX 100020

using namespace std;

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

int TT[NMAX], RG[NMAX];
int N, M;

int root(int x){
    int R;

    for(R = x; R != TT[R] ; R = TT[R]);

    return R;
}

void unite(int x, int y){
    if (RG[x] > RG[y])
        TT[y] = x;
    else
        TT[x] = y;

    if (RG[x] == RG[y]) RG[y]++;
}

int main(){
    int i, x, y, cd;

    fin>>N>>M;

    for (i = 1; i <= N; i++){
        TT[i] = i;
        RG[i] = 1;
    }

    for (i = 1; i <= M; i++){
        fin>>cd>>x>>y;

        if (cd == 2){
            if (root(x) == root(y))
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }
        else
            unite(root(x), root(y));
    }

    return 0;
}