Cod sursa(job #1511769)

Utilizator abel1090Abel Putovits abel1090 Data 27 octombrie 2015 09:26:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>

using namespace std;

int query(vector<int>& root, int x) {
    int curr = x;
    while(root[curr] != curr) {
        curr = root[curr];
    }
    root[x] = curr;
    return root[x];
}

void unite(vector<int>& root, vector<int>& rang, int x, int y) {
    int rootX, rootY;
    rootX = query(root, x);
    rootY = query(root, y);

    if(rang[rootX] == rang[rootY]) {
        root[rootX] = rootY;
        ++rang[rootY];
    }
    if(rang[rootX] < rang[rootY]) {
        root[rootX] = rootY;
    }
    if(rang[rootX] > rang[rootY]) {
        root[rootY] = rootX;
    }
}

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

    int N, M;
    fin >> N >> M;

    vector<int> root(N);
    vector<int> rang(N, 1);
    for(int i=0; i<N; ++i) {
        root[i] = i;
    }

    int a, b, c;
    for(int i=0; i<M; ++i) {
        fin >> a >> b >> c;
        if(a == 1) {
            unite(root, rang, b-1, c-1);
        }
        if(a == 2) {
            if(query(root, b-1) == query(root, c-1))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    return 0;
}