Cod sursa(job #2557510)

Utilizator rexlcdTenea Mihai rexlcd Data 25 februarie 2020 20:46:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>

using namespace std;

const int nmax = 1e5 + 2;

int rang[nmax], to[nmax];

inline int find(int x)
{
    int rad = x;
    while(to[rad] != rad)
        rad = to[rad];
    while(to[x] != x)
    {
        int y = to[x];
        to[x] = rad;
        x = y;
    }

    return rad;
}

inline void unite(int x, int y)
{
    if(rang[x] > rang[y])
        to[y] = x;
    else
        to[x] = y;
    if(rang[x] == rang[y])
        rang[x]++;
}

int main()
{
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    int n, q; f >> n >> q;
    for(int i = 1; i <= n; i++)
    {
        rang[i] = 1;
        to[i] = i;
    }

    while(q--)
    {
        int c, a, b; f >> c >> a >> b;
        if(c == 1)
            unite(find(a), find(b));
        else
            g << (find(a) == find(b) ? "DA\n" : "NU\n");
    }

    f.close();
    g.close();
    return 0;
}