Cod sursa(job #2312849)

Utilizator Moise_AndreiMoise Andrei Moise_Andrei Data 5 ianuarie 2019 16:54:19
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int v[100005];
int c[100005];
int n, m;
int f(int x)
{
    while(v[x] != x)
    {
        v[x] = v[v[x]];
        x = v[x];
    }
    return x;
}

void unire(int a, int b)
{
    int x = f(a), y = f(b);
    if(c[x] < c[y])
        v[x] = y;
    else if (c[y] < c[x])
        v[y] = x;
    else
    {
        v[x] = y;
        c[y]++;
    }
}
int main()
{
    in >> n >> m;
    for(int i = 1; i <= n; i ++)
        v[i] = i;
    while(m --)
    {
        int t, a, b;
        in >> t >> a >> b;
        if(t == 1)
            unire(a, b);
        else
        {
            if(f(a) == f(b))
                out << "DA";
            else
                out << "NU";
        }
    }
    return 0;
}