Cod sursa(job #2942743)

Utilizator simonatudoroiuTudoroiu Simona simonatudoroiu Data 19 noiembrie 2022 23:52:42
Problema Paduri de multimi disjuncte Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int gaseste_radacina(int nod, vector<int>& tata)
{
    if(tata[nod] == nod)
        return nod;
    else
    {
        int c = nod, x;
        while(tata[c] != c)
        {
            c = tata[c];
        }

        while(tata[nod] != nod)
        {
            x = tata[nod];
            tata[nod] = c;
            nod = x;
        }

        return c;
    }
}
int main()
{
    int n,m,a,b,c;
    vector<vector<int>> list;
    vector<int> tata, rang;
    fin>>n>>m;
    for(int i=0;i<=n;i++)
    {
        tata.push_back(i);
        rang.push_back(1);
        list.push_back({});
    }
    for(int x=1;x<=m;x++)
    {
        fin>>a>>b>>c;
        if(a == 1)
        {
            if(rang[b]<rang[c])
                tata[b] = c;
            else
                tata[c] = b;
            if(rang[b] == rang[c])
                rang[c]++;
        }
        else
        {

            if(gaseste_radacina(b,tata) == gaseste_radacina(c,tata))
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }

    }
    fin.close();
    fout.close();
    return 0;
}