Cod sursa(job #2841640)

Utilizator AdrianDiaconitaAdrian Diaconita AdrianDiaconita Data 30 ianuarie 2022 01:01:41
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
using namespace std;

ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");

const int NMAX = 100001;
int n, m, ROOT[NMAX], GR[NMAX];
int root(int x);
void unite (int x, int y);
int main()
{
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        ROOT[i] = i;
        GR[i] = 1;
    }

    int x,y,q;
    for (int i = 1; i <= m; ++i)
    {
        fin >> q >> x >> y;
        if (q == 1) unite(x,y);
        else {
            if (root(x) == root(y)) fout << "DA" << ' ';
            else fout << "NU" << ' ';
        }
    }
    return 0;
}
int root(int x)
{
    if (x == ROOT[x]) return x;
    ROOT[x] = root(ROOT[x]);
}

void unite(int x, int y)
{
    if (GR[x] > GR[y])
    {
        ROOT[y] = ROOT[x];
        GR[x] += GR[y];
    }
    else {
        ROOT[x] = ROOT[y];
        GR[y] += GR[x];
    }
}