Cod sursa(job #2263838)

Utilizator Bogdy_PPrunescu Bogdan Bogdy_P Data 19 octombrie 2018 13:41:43
Problema Paduri de multimi disjuncte Scor 100
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 TT[1000010], RG[1000010];
int get_root(int x)
{
    int R = x;
    while(R != TT[R]) R = TT[R];
    while(TT[x] != x)
    {
        int y = TT[x];
        TT[x] = R;
        x = y;
    }
    return R;
}
void unite(int x, int y)
{
    if(RG[x] > RG[y])
         TT[y] = x;
    else TT[x] = y;
    if(RG[x] == RG[y])RG[x]++;
}

int C, N, M, x, y;
int main()
{
    in >> N >> M;
    for(int i = 1;i <= N;i++)
    {
        TT[i] = i;
        RG[i] = 1;
    }
    for(int i = 1;i <= M;i++)
    {
        in >> C >> x >> y;
        if(C == 1) unite(get_root(x), get_root(y));
        else if(get_root(x) == get_root(y)) out << "DA" << '\n';
        else out << "NU" << '\n';
    }
    return 0;
}