Cod sursa(job #2700914)

Utilizator cyg_mihaizMIHAI ZARAFIU cyg_mihaiz Data 29 ianuarie 2021 12:03:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>

using namespace std;
const int NMAX = 100000;

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

int tree[NMAX + 5], height[NMAX + 5];

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

int query(int node)
{
    int i,aux;
    for(i = node; tree[i] != i; i = tree[i]);
    for(; tree[node] != node;)
    {
        aux = tree[node];
        tree[node] = i;
        node = aux;
    }
    return i;
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);

    int n,m,i,op,x,y;
    fin >> n >> m;
    for(i = 1; i <= n; i++)
    {
        tree[i] = i;
        height[i] = 1;
    }
    while(m--)
    {
        fin >> op >> x >> y;
        if(op == 1)
            unite(query(x),query(y));
        else
            if(query(x) == query(y))
                fout << "DA\n";
            else
                fout << "NU\n";
    }
    return 0;
}