Cod sursa(job #1775695)

Utilizator danielNiculaeDaniel Niculae danielNiculae Data 10 octombrie 2016 17:05:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include "fstream"

using namespace std;

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

const int NMAX = 100005;

int N, M;
int parent[NMAX];

void merge(int x, int y) {
    int depthX = 0, depthY = 0;
    int ancestorX = x, ancestorY = y;
    while(parent[ancestorX]) {
        ancestorX = parent[ancestorX];
        depthX++;
    }

    while(parent[ancestorY]) {
        ancestorY = parent[ancestorY];
        depthY++;
    }

    if(depthX < depthY) {
        parent[ancestorX] = ancestorY;
    }
    else {
        parent[ancestorY] = ancestorX;
    }

//    for(int i = 1 ; i <= N ; i++) {
//        fout << parent[i] << " ";
//    }
//    fout << "\n";
//    fout.flush();
}

bool sameAncestor(int x, int y) {
    int ancestorX = x, ancestorY = y;
    while(parent[ancestorX]) {
        ancestorX = parent[ancestorX];
    }

    while(parent[ancestorY]) {
        ancestorY = parent[ancestorY];
    }

    return ancestorX == ancestorY;
}

int main() {
    int N, M;

    fin >> N >> M;

    for(int i = 1 ; i <= M ; i++) {
        int type, x, y;
        fin >> type >> x >> y;
        if(type == 1) {
            merge(x, y);
        }
        else {
            if(sameAncestor(x, y)) {
                fout << "DA" << "\n";
            }
            else {
                fout << "NU" << "\n";
            }
        }
    }

    return 0;
}