Cod sursa(job #2945597)

Utilizator JovialJokerFlorea George JovialJoker Data 23 noiembrie 2022 22:22:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

vector<int> tata(100001), rang(100001);
int N, M;

int findAncestor(int k){
    ///we recursively traverse the fathers vector to find the one node that doesn't have a father
    if(tata[k]) {
        tata[k] = findAncestor(tata[k]);
        return tata[k];
    }
    return k;
}

void Union(int x, int y){
    if(x != y) {
        ///if the x node has a bigger rank than y, than the father of y is x
        /// so that we unite the 2 sets under one node
        if (rang[x] > rang[y])
            tata[y] = x;
        else
            tata[x] = y;
        ///if 2 nodes have the same rank, we arbitrary choose x and increment its rank
        if(rang[x] == rang[y])
            rang[x]++;
    }
}

int main(){
    f >> N >> M;
    int op, x, y;
    while (M--){
        f >> op >> x >> y;
        if(op == 1){
            Union(findAncestor(x), findAncestor(y));
        }
        else{
            if(findAncestor(x) == findAncestor(y))
                g << "DA\n";
            else
                g << "NU\n";
        }
    }
    f.close();
    g.close();
    return 0;
}