Cod sursa(job #2325289)

Utilizator DawlauAndrei Blahovici Dawlau Data 22 ianuarie 2019 13:58:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>

using namespace std;

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

void Unite(vector <int> &Rank, vector <int> &Father, int node1, int node2){

    if(Rank[node1] > Rank[node2])
        Father[node2] = node1;
    else Father[node1] = node2;

    if(Rank[node1] == Rank[node2])
        ++Rank[node2];
}

int Find(vector <int> &Father, int node){

    int root;
    for(root = node; Father[root] != root; root = Father[root]);

    while(node != root){

        int auxNode = node;
        node = Father[node];
        Father[auxNode] = root;
    }

    return root;
}

int main(){

    int N, Q;
    fin >> N >> Q;

    vector <int> Father(1 + N);
    vector <int> Rank(1 + N);

    for(int node = 1; node <= N; ++node){

        Father[node] = node;
        Rank[node] = 1;
    }

    for(; Q; --Q){

        int code, node1, node2;
        fin >> code >> node1 >> node2;

        if(code == 1){

            int root1 = Find(Father, node1);
            int root2 = Find(Father, node2);

            Unite(Rank, Father, root1, root2);
        }
        else if(Find(Father, node1) != Find(Father, node2))
            fout << "NU\n";
        else fout << "DA\n";
    }
}