Cod sursa(job #3304085)

Utilizator unomMirel Costel unom Data 20 iulie 2025 13:15:56
Problema Heapuri cu reuniune Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
//merge si cu pq cu small to large da e mai misto asa :)

#include <fstream>
#include <queue>

using namespace std;

struct node
{
    int val;
    node *copil_st, *urmator;
};

ifstream in("mergeheap.in");
ofstream out("mergeheap.out");
int n, q;
node *heaps[105];

void adauga_copil(node *tata, node *copil)
{
    if(tata->copil_st == NULL)
    {
        tata->copil_st = copil;
    }
    else
    {
        copil->urmator = tata->copil_st;
        tata->copil_st = copil;
    }
}

node *uneste(node *a, node *b)
{
    if(a == NULL)
    {
        return b;
    }
    if(b == NULL)
    {
        return a;
    }

    if(a->val > b->val)
    {
        adauga_copil(a, b);
        return a;
    }
    else
    {
        adauga_copil(b, a);
        return b;
    }
}

void adauga(int ind, int val)
{
    node *nou = new node;
    nou->val = val;
    nou->copil_st = NULL;
    nou->urmator = NULL;

    heaps[ind] = uneste(heaps[ind], nou);
}

int top(int ind)
{
    return heaps[ind]->val;
}

node *uneste_rapid(node *nod)
{
    if(nod == NULL || nod->urmator == NULL)
    {
        return nod;
    }

    node *a, *b, *nou;

    a = nod;
    b = nod->urmator;
    nou = nod->urmator->urmator;

    a->urmator = NULL;
    b->urmator = NULL;

    return uneste(uneste(a, b), uneste_rapid(nou));
}

void sterge(int ind)
{
    heaps[ind] = uneste_rapid(heaps[ind]->copil_st);
}

int main()
{
    in>>n>>q;

    for(int i = 1; i<=n; i++)
    {
        heaps[i] = NULL;
    }

    int a, b, c;
    while(q--)
    {
        in>>a;

        if(a == 1)
        {
            in>>b>>c;

            adauga(b, c);
        }
        else if(a == 2)
        {
            in>>b;

            out<<top(b)<<'\n';
            sterge(b);
        }
        else
        {
            in>>b>>c;

            heaps[b] = uneste(heaps[b], heaps[c]);
            heaps[c] = NULL;
        }
    }

    return 0;
}