Cod sursa(job #2390660)

Utilizator toni123Mititelu George-Antonio toni123 Data 28 martie 2019 11:22:06
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    int n, m, x, y, operatie;
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    fin >> n >> m;

    vector<int> comp(n+1);
    vector<vector<int>> compConex(n+1);

    for(int i = 1; i <= n; i++)
    {
        comp[i] = i;
        compConex[i].push_back(i);
    }

    for(int i = 0; i < m; i++)
    {
        fin >> operatie >> x >> y;
        if(operatie == 1)
        {
            x = comp[x];
            y = comp[y];
            if(x != y)
                if(compConex[x].size() < compConex[y].size())
                {
                    for(auto j : compConex[x])
                    {
                        comp[j] = y;
                        compConex[y].push_back(j);
                    }
                    compConex[x].clear();
                }
                else
                {
                    for(auto j : compConex[y])
                    {
                        comp[j] = x;
                        compConex[x].push_back(j);
                    }
                    compConex[y].clear();
                }
        }
        else
            if(comp[x] != comp[y])
                fout << "NU" << endl;
            else
                fout << "DA" << endl;
    }

    fin.close();
    fout.close();

    return 0;
}