Cod sursa(job #2062589)

Utilizator DianaVelciovVelciov Diana DianaVelciov Data 10 noiembrie 2017 16:56:12
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");
//ifstream in("date.in");
//ofstream out("date.out");

const int N_MAX = 1000;
int TT[N_MAX + 5], r[N_MAX + 5];
int N, M;

int root(int x){
    while (TT[x] != x)
        x = TT[x];
    return x;
}

void unite (int x, int y){
    if (r[x] < r[y])
        TT[x] = y;
    if (r[x] > r[y])
        TT[y] = x;
    if (r[x] == r[y]){
        TT[y] = x;
        r[x]++;
    }
}

int main(){
    in >> N >> M;
    for (int i = 1; i <= N; ++i)
        TT[i] = i;
    for (int i = 1; i <= M ; ++i){
            int op, x, y; in >> op >> x >> y;
        if (op == 1)
            unite(root(x), root(y));
        if (op == 2)
            if (root(x) == root(y))
                out << "DA\n";
            else out << "NU\n";
    }
    in.close(); out.close();
    return 0;
}