Cod sursa(job #2015037)

Utilizator workwork work work Data 24 august 2017 22:32:50
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <bits/stdc++.h>

using namespace std;

FILE *F=fopen("disjoint.in", "r"), *G=fopen("disjoint.out", "w");

int n, m, q, x, y, tx, ty, t[100006], rg[100006];

int fnd(int x)
{
    int r, y;

    for(r = x; r != t[r]; r = t[r]);

    while(x != t[x])
    {
        y = t[x];
        t[x] = r;
        x = y;
    }
    return r;
}

void Unite(int x, int y)
{
    if(rg[x] >= rg[y]) t[y] = x;
    else t[x] = y;

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

int main()
{
    fscanf(F, "%d %d ", &n, &m);
    for(int i = 1; i <= n; ++ i) t[i] = i, rg[i] = 1;
    for(int i = 0; i < m; ++ i)
    {
        fscanf(F, "%d %d %d ", &q, &x, &y);
        tx = fnd(x); ty = fnd(y);
        if(q == 2)
        {
            tx == ty ? fprintf(G, "DA\n") : fprintf(G, "NU\n");
        }
        else Unite(tx, ty);
    }
    return 0;
}