Cod sursa(job #1987348)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 30 mai 2017 14:29:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

using namespace std;
int N, M;

vector<vector<int> > arrays;
vector<int> where;

void megaPouring(int from, int to)
{
    while(!arrays[from].empty()) {
        arrays[to].push_back( arrays[from].back() );
        arrays[from].pop_back();
        where[arrays[to].back()] = to;
    }
    arrays[from].shrink_to_fit();
}

int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    ios::sync_with_stdio(false);
    scanf("%d%d", &N, &M);
    arrays.resize(N + 1);
    where.resize(N + 1);

    for(int i = 1; i <= N; ++i)
    {
        arrays[i].push_back(i);
        where[i] = i;
    }


    int tip, a, b;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d%d%d",&tip, &a, &b);
        if(tip == 2) {
            if(where[a] == where[b])
                printf("DA\n");
            else
                printf("NU\n");
            continue;
        }

        int x, y;
        x = where[a];
        y = where[b];
        if(arrays[x].size() > arrays[y].size())
            swap(x, y);
        megaPouring(x, y);
    }

    return 0;
}