Cod sursa(job #2010774)

Utilizator vladm98Munteanu Vlad vladm98 Data 14 august 2017 12:41:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
using namespace std;
int tata[100001], n, i, j, card[100001], m, verif, x, y;
vector <int> graf[100001];
void schimba_tata (int nod, int tata_nou)
{
    tata[nod] = tata_nou;
    graf[tata_nou].push_back(nod);
    for (auto x:graf[nod])
        schimba_tata(x, tata_nou);
    graf[nod].clear();
}
int stapan (int nod)
{
    int rege = nod, copie;
    while (tata[rege] != rege)
        rege = tata[rege];
    while (tata[nod] != nod)
    {
        copie = nod;
        nod = tata[nod];
        tata[copie] = rege;
    }
    return rege;
}
void unire (int a, int b)
{
    int st1 = stapan(a), st2 = stapan(b);
    if (st2 == st1)
        return ;
    if (card[st1] > card[st2])
    {
        card[st1]+=card[st2];
        schimba_tata(st2, st1);
    }
    else
    {
        card[st2] += card[st1];
        schimba_tata(st1, st2);
    }
}
int main()
{
    ofstream fout ("disjoint.out");
    ifstream fin ("disjoint.in");
    fin >> n >> m;
    for (i=1; i<=n; ++i)
    {
        tata[i] = i;
        card[i] = 1;
    }
    for (i=0; i<m; ++i)
    {
        fin >> verif >> x >> y;
        if (verif == 1)
            unire(x, y);
        if (verif == 2)
        {
            if (stapan(x) == stapan(y))
                fout << "DA\n";
            else fout << "NU\n";
        }
    }
    return 0;
}