Cod sursa(job #2397171)

Utilizator klamathixMihai Calancea klamathix Data 4 aprilie 2019 11:19:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> parent, depth;

int root(int x) {
    if(x == parent[x])
        return x;
    int ans = root(parent[x]);

    //Comprimam drumul pentru apeluri viitoare
    parent[x] = ans;
    return ans;
}

void unite(int x, int y) {
    //Unim arborele cu adancimea mai mica de cel cu adancimea mai mare
    if(depth[x] < depth[y]) {
        parent[x] = y;
    } else {
        parent[y] = x;
    }
    
    //Daca adancimile erau egale, radacina noua este x
    //(vezi linia 21), deci incrementam depth[x]

    if(depth[x] == depth[y]) {
        depth[x] += 1;
    }
}

bool sameComp(int x, int y) {
    return root(x) == root(y);
}

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

    int n, m; fin >> n >> m;
    
    parent = vector<int> (n, 0);
    depth = vector<int> (n, 0);

    for(int i = 0; i < n; i += 1) {
        parent[i] = i;
    }

    for(int i = 0; i < m; i += 1) {
        int type, x, y; fin >> type >> x >> y;

        x -= 1, y -= 1;

        if(type == 1) {
            //Intotdeauna lucram cu radacinile
            unite(root(x), root(y)); 
        } else {
            bool ans = sameComp(x, y);
            if(ans) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
}