Cod sursa(job #2565241)

Utilizator Fatu_SamuelFatu Samuel Fatu_Samuel Data 2 martie 2020 12:55:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 100005;

int n, m;
int p[nmax], rnk[nmax];

int root(int nod)
{
    while (nod != p[nod])
    {
        p[nod] = p[p[nod]];
        nod = p[nod];
    }

    return nod;
}

void unite(int x, int y)
{
    if (rnk[x] > rnk[y])
        p[y] = x;
    else
        p[x] = y;

    if (rnk[x] == rnk[y])
        rnk[y]++;
}

int main()
{
    fin >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        p[i] = i;
        rnk[i] = 1;
    }

    for (int i = 1; i <= m; i++)
    {
        int cerinta, x, y;

        fin >> cerinta >> x >> y;

        if (cerinta == 1)
            unite(root(x), root(y));
        else
        {
            if (root(x) == root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

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