Cod sursa(job #1367221)

Utilizator viuscenkoViktor Iuscenko viuscenko Data 1 martie 2015 18:20:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

using namespace std;

#define     mp              make_pair
#define     fs              first
#define     sc              second
#define     pob             pop_back
#define     pub             push_back
#define     eps             1E-7
#define     sz(a)           a.size()
#define     count_one       __builtin_popcount;
#define     count_onell     __builtin_popcountll;
#define     fastIO          ios_base::sync_with_stdio(false)
#define     PI              (acos(-1.0))
#define     linf            (1LL<<62)//>4e18
#define     inf             (0x7f7f7f7f)//>2e9

#define DEBUG 1
#ifdef DEBUG
#define D(x) x
#else
#define D(x)
#endif

#define MAXN 100010

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

int n, m;
int cod, xx, yy;
pair<int, int> dis[MAXN];

int find(int x) {
    if(dis[x].first != x)
        dis[x].first = find(dis[x].first);

    return dis[x].first;
}

void unite(int x, int y) {
    int xRoot = find(x);
    int yRoot = find(y);
    if (xRoot == yRoot)
        return;

    if (dis[xRoot].second < dis[yRoot].second)
        dis[xRoot].first = yRoot;
    else if (dis[yRoot].second < dis[xRoot].second)
        dis[yRoot].first = xRoot;
    else
        dis[yRoot].first = xRoot,
        dis[xRoot].second++;
}

int main()
{
    fscanf(in, "%d%d", &n, &m);
    for(int i = 1; i <= n; ++i)
        dis[i] = mp(i, 0);
    while (m--) {
        fscanf(in, "%d%d%d", &cod, &xx, &yy);
        if(cod == 1)
            unite(xx, yy);
        else {
            if(find(xx) == find(yy))
                fprintf(out, "DA\n");
            else
                fprintf(out, "NU\n");
        }
    }
    return 0;
}