Cod sursa(job #1888057)

Utilizator MaligMamaliga cu smantana Malig Data 21 februarie 2017 21:46:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<iostream>
#include<fstream>
#include<cmath>
#include<algorithm>

using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");

const int NMax = 100000 + 5;
// sets are represented as trees

int N,M;
int dad[NMax],height[NMax];
// dad[i] = the father node of node i in its tree
// height[i] = the (maximum) height of the tree that has node i in it (it may decrease)


int findRoot(int);
void uniteSets(int,int);
// findRoot(x) finds the root of the tree node x is in and updates the root of all the nodes on the path
// uniteSets(x,y) adds the tree with the smallest height to the tree with the biggest height
// (from the two trees that contain x and y) and updates the height of the bigger tree
// (which can only increase when they have the same height)

int main() {
    in>>N>>M;

    for (int i=1;i<=N;++i) {
        dad[i] = i;
        height[i] = 1;
    }

    for (int i=1;i<=M;++i) {
        int cod,x,y;
        in>>cod>>x>>y;
        if (cod==1) {
            uniteSets(x,y);
        }
        else {
            int root1 = findRoot(x),
                root2 = findRoot(y);
            if (root1==root2) {
                out<<"DA\n";
            }
            else {
                out<<"NU\n";
            }
        }
    }

    in.close();out.close();
    return 0;
}

int findRoot(int nod) {
    if (dad[nod] == nod) {
        return nod;
    }
    dad[nod] = findRoot(dad[nod]);
    return dad[nod];
}

void uniteSets(int x,int y) {
    int root1 = findRoot(x),
        root2 = findRoot(y);
    if (height[root1]>=height[root2]) {
        if (height[root1]==height[root2]) {
            ++height[root1];
        }

        dad[root2] = root1;
    }
    else {
        dad[root1] = root2;
    }
}