Cod sursa(job #3130950)

Utilizator opreaopreacalin@gmail.comCalin Oprea [email protected] Data 18 mai 2023 21:11:56
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include<stdio.h>
#include <fstream>
using namespace std;
ifstream in("in");
ofstream out("out");

#define nmax 200001
int heap[nmax],heapIN[nmax],m,auxIN[nmax],ind;


void showHeap()
{
    out<<heap[1]<<endl;
}
void shiftTWO(int x, int y)
{
    int aux=heap[x];
    heap[x]=heap[y];
    heap[y]=aux;

    aux=heapIN[x];
    heapIN[x]=heapIN[y];
    heapIN[y]=aux;

    aux=auxIN[heapIN[x]];
    auxIN[heapIN[x]]=auxIN[heapIN[y]];
    auxIN[heapIN[y]]=aux;
}
void shiftOne(int k)
{
    int child=1;
    while (child)
    {
        child=0;
        if (2*k <= m)
        {
            child= 2 * k;
            if (2*k+1 <= m && heap[2 * k + 1] < heap[2 * k])
                child= 2 * k + 1;
            if (heap[child] > heap[k]) child=0;
        }
        if (child)
        {
            shiftTWO(k, child);
            k=child;
        }
    }
}
void sterge(int a)
{
    heap[auxIN[a]]=heap[m];
    m--;
    shiftOne(auxIN[a]);
}
void percolate(int k)
{
    while (k>1 && heap[k]<heap[k/2])
    {
        shiftTWO(k, k / 2);
        k=k/2;
    }
}
void adauga(int a)
{
    heap[++m]=a;
    heapIN[m]=++ind;
    auxIN[ind]=m;
    percolate(m);
}

int main()
{
    int n,op,x;

    in >> n;
    for(int i=1;i<=n; i++)
    {
        in >> op;
        if (op == 1)
        {
            in >> x;
            adauga(x);
        }
        else
        if (op == 2)
        {
            in >> x;
            sterge(x);
        }
        else
            showHeap();
    }
    return 0;
}