Cod sursa(job #1497030)

Utilizator serbanSlincu Serban serban Data 5 octombrie 2015 23:00:11
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>

using namespace std;

int v[100005];
int lg[100005];

int first(int a) {
    a = v[a];
    while(a != v[a])
        a = v[a];
    return a;
}

int bun(int a, int b) {
    int A = first(a);
    int B = first(b);
    return (A == B);
}

void mergeList(int a, int b) {
    int A = first(a);
    int B = first(b);
    if(lg[A] > lg[B])
        v[B] = v[A];
    else v[A] = v[B];
    if(lg[A] == lg[B])
        lg[A] ++;
}

int main()
{
    ios::sync_with_stdio(false);
    ifstream cn("disjoint.in");
    ofstream co("disjoint.out");
    int n, m;
    int x, y, t;
    cn >> n >> m;

    for(int i = 1; i <= n; i ++) {
        v[i] = i;
        lg[i] = 1;
    }

    for(int i = 1; i <= m; i ++) {
        cn >> t >> x >> y;
        if(t == 1) mergeList(x, y);
        else {
            if(bun(x, y))
                co << "DA\n";
            else
                co << "NU\n";
        }
    }
    cn.close();
    co.close();
    return 0;
}