Cod sursa(job #2390686)

Utilizator toni123Mititelu George-Antonio toni123 Data 28 martie 2019 11:31:38
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 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(compConex[x].size() < compConex[y].size())
            {
                for(auto j : compConex[x])
                {
                    comp[j] = y;
                    compConex[y].push_back(j);
                    j = 0;
                }
            }
            else
            {
                for(auto j : compConex[y])
                {
                    comp[j] = x;
                    compConex[x].push_back(j);
                    j = 0;
                }
            }
        }
        else
            if(operatie == 2){
                if(comp[x] != comp[y])
                    fout << "NU" << endl;
                else
                    fout << "DA" << endl;
            }
    }

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

    return 0;
}