Cod sursa(job #1987345)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 30 mai 2017 14:24:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 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()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    ios::sync_with_stdio(false);
    fin >> 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)
    {
        fin >> tip >> a >> b;
        if(tip == 2) {
            if(where[a] == where[b])
                fout << "DA\n";
            else
                fout << "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;
}