Cod sursa(job #2472002)

Utilizator Horia14Horia Banciu Horia14 Data 11 octombrie 2019 21:32:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include<cstdio>
#define MAX_N 100000

int p[MAX_N+1], h[MAX_N+1], n, m;

void Init(int n) {
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        h[i] = 1;
    }
}

inline int Find(int x) {
    int r, aux;
    r = x;
    while(p[r] != r)
        r = p[r];
    while(p[x] != r) {
        aux = p[x];
        p[x] = r;
        x = aux;
    }
    return r;
}

void Union(int x, int y) {
    int rx, ry;
    rx = Find(x);
    ry = Find(y);
    if(h[rx] < h[ry])
        p[rx] = ry;
    else if(h[rx] > h[ry])
        p[ry] = rx;
    else {
        p[rx] = ry;
        h[ry]++;
    }
}

int main() {
    int op, x, y;
    bool val;
    FILE* fin, *fout;
    fin = fopen("disjoint.in","r");
    fout = fopen("disjoint.out","w");
    fscanf(fin,"%d%d",&n,&m);
    Init(n);
    for(int i = 1; i <= m; i++) {
        fscanf(fin,"%d%d%d",&op,&x,&y);
        if(op == 1)
            Union(x,y);
        else {
            val = Find(x) == Find(y);
            if(val)
                fprintf(fout, "DA\n");
            else fprintf(fout, "NU\n");
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}