Cod sursa(job #2707255)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 16 februarie 2021 18:44:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <stdio.h>
#include <vector>

using namespace std;

int find_boss(int x, vector<int> & boss) {
    if (x == boss[x]) {
        return x;
    }
    boss[x] = find_boss(boss[x], boss);
    return boss[x];
}

void merge(int x, int y, vector<int> & boss, vector<int> & tree_height_limit) {
    int boss_x = find_boss(x, boss);
    int boss_y = find_boss(y, boss);
    if (tree_height_limit[boss_x] < tree_height_limit[boss_y]) {
        boss[boss_x] = boss_y;
    } else {
        boss[boss_y] = boss_x;
        if (tree_height_limit[boss_x] == tree_height_limit[boss_y]) {
            tree_height_limit[boss_y]++;
        }
    }
}

int main() {
    FILE * fin, * fout;
    int n, m, op, x, y;

    fin = fopen("disjoint.in", "r");
    fout = fopen("disjoint.out", "w");

    fscanf(fin, "%d%d", &n, &m);
    vector<int> tree_height_limit(n, 1);
    vector<int> boss(n);
    for (int i = 0; i < n; i++) {
        boss[i] = i;
    }

    for (int i = 0; i < m; i++) {
        fscanf(fin, "%d%d%d", &op, &x, &y);
        x--;
        y--;

        if (op == 1) {
            merge(x, y, boss, tree_height_limit);
        } else {
            const char * ans = 
                (find_boss(x, boss) == find_boss(y, boss)) ? 
                "DA" : 
                "NU";
            fprintf(fout, "%s\n", ans);
        }
    }

    fclose(fin);
    fclose(fout);

    return 0;
}