Cod sursa(job #1888067)

Utilizator MaligMamaliga cu smantana Malig Data 21 februarie 2017 21:54:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 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)

const int strMax = 20 * NMax;
char c[strMax];
int pos = 0;

int getNumber() {
    int nr = 0;

    while ( !('0'<=c[pos] && c[pos]<='9') ) {
        ++pos;
    }

    while ('0'<=c[pos] && c[pos]
           <='9') {
        nr = nr * 10 + c[pos++] - '0';
    }
    return nr;
}


int main() {
    in.getline(c,strMax,'%');
    N = getNumber();
    M = getNumber();


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

    for (int i=1;i<=M;++i) {
        int cod,x,y;
        cod = getNumber();
        x = getNumber();
        y = getNumber();
        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;
    }
}