Cod sursa(job #3260285)

Utilizator PreparationTurturica Eric Preparation Data 1 decembrie 2024 13:57:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <iostream>
#define MAX_N 100005

int n, m;
int root[MAX_N];
int siz[MAX_N];

int getRoot(int pos)
{
    while (root[pos] != root[root[pos]]) {
        root[pos] = root[root[pos]];
        pos = root[pos];
    }
    return root[pos];
}

void unite(int x, int y)
{
    x = getRoot(x);
    y = getRoot(y);
    if (siz[x] > siz[y]) {
        root[y] = x;
        siz[x] += siz[y];
    } else {
        root[x] = y;
        siz[y] += siz[x];
    }
}

int main()
{
    FILE *fin = fopen("disjoint.in", "r");
    FILE *fout = fopen("disjoint.out", "w");
    fscanf(fin, "%d %d", &n, &m);
    for (int i = 0; i < n; i++)
        root[i] = i;
    for (int i = 0; i < m; i++) {
        int t, x, y;
        fscanf(fin, "%d %d %d", &t, &x, &y);
        x--;
        y--;
        if (t == 1) {
            unite(x, y);
        } else {
            if (getRoot(x) == getRoot(y))
                fprintf(fout, "DA\n");
            else
                fprintf(fout, "NU\n");
        }
    }
}