Cod sursa(job #1699624)

Utilizator cosmin79Carabet Cosmin Andrei cosmin79 Data 7 mai 2016 22:57:08
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <cstdio>
const int NMAX = 100505;

int N, M, par[NMAX], rnk[NMAX];

void init() {
    for (int i = 1; i <= N; i++) {
        par[i] = i;
    }
}

inline void pathCompression(int startNode, int endNode) {
    int aux;
    while (startNode != endNode) {
        aux = par[startNode];
        par[startNode] = endNode;
        startNode = aux;
    }
}

inline bool isRoot(int node) {
    return par[node] == node;
}

inline bool hasEnded(int x, int y, bool query) {
    if (x == y) {
        if (query) {
            printf("DA\n");
        }
        return true;
    }

    bool stop = false;
    if (isRoot(x) && rnk[x] < rnk[y]) {
        if (!query) {
            par[x] = y;
        }
        stop = true;
    } else if (isRoot(y) && rnk[y] < rnk[x]) {
        if (!query) {
            par[y] = x;
        }
        stop = true;
    } else if (isRoot(x) && isRoot(y) && rnk[x] == rnk[y]) {
        if (!query) {
            par[x] = y;
            rnk[y]++;
        }
        stop = true;
    }

    if (stop && query) {
        printf("NU\n");
    }
    return stop;
}

void go(int x, int y, bool query) {
    int endX = x, endY = y;
    while (!hasEnded(endX, endY, query)) {
        if (rnk[endX] < rnk[endY]) {
            endX = par[endX];
        } else {
            endY = par[endY];
        }
    }

    pathCompression(x, par[endX]);
    pathCompression(y, par[endY]);
}

int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    scanf("%d%d", &N, &M);
    init();
    int type, x, y;
    for (int i = 1; i <= M; i++) {
        scanf("%d%d%d", &type, &x, &y);
        if (type == 1) {
            go(x, y, false);
        } else {
            go(x, y, true);
        }
    }
    return 0;
}