Cod sursa(job #997795)

Utilizator manutrutaEmanuel Truta manutruta Data 14 septembrie 2013 21:30:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
# include <cstdio>
using namespace std;

# define NMAX 100020

FILE *f = fopen("disjoint.in", "r");
FILE *g = fopen("disjoint.out", "w");

int TT[NMAX], RG[NMAX];
int N, M;

int find(int x)
{
    int R;

    for (R = x; TT[R] != R; R = TT[R]);

    while (TT[x] != x) {
        x = TT[x];
        TT[x] = R;
    }
    return R;
}

void unite(int x, int y)
{
    if (RG[x] > RG[y]) {
        TT[y] = x;
    } else {
        TT[x] = y;
    }

    if (RG[x] == RG[y]) RG[y]++;
}

int main()
{
    fscanf(f, "%d %d ", &N, &M);

    for (int i = 1; i <= N; i++) {
        TT[i] = i;
        RG[i] = 1;
    }


    for (int i = 1; i <= M; i++) {
        int x, y, cd;
        fscanf(f, "%d %d %d", &cd, &x, &y);

        if (cd == 2) {
            if (find(x) == find(y)) {
                fprintf(g, "DA\n");
            } else {
                fprintf(g, "NU\n");
            }
        } else {
            unite(find(x), find(y));
        }
    }

    return 0;
}