Cod sursa(job #2864054)

Utilizator CiuiGinjoveanu Dragos Ciui Data 7 martie 2022 15:40:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int MAX_SIZE = 100005;
int representants[MAX_SIZE];

int findRoot(int peak) {
    int root = representants[peak];
    while (root != representants[root]) {
        root = representants[root];
    }
    while (representants[peak] != root) {
        int aux = representants[peak];
        representants[peak] = root;
        peak = aux;
    }
    return root;
}

void unite(int start, int end) {
    representants[start] = representants[end];
}

int main() {
    int peaks, arches;
    fin >> peaks >> arches;
    for (int i = 1; i <= peaks; ++i) {
        representants[i] = i;
    }
    for (int i = 1; i <= arches; ++i) {
        int operation, start, end;
        fin >> operation >> start >> end;
        if (operation == 1) {
            unite(findRoot(start), findRoot(end));
        } else {
            if (findRoot(start) == findRoot(end)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}