Cod sursa(job #3130964)

Utilizator opreaopreacalin@gmail.comCalin Oprea [email protected] Data 18 mai 2023 21:35:26
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include<stdio.h>
#include <fstream>
#define nmax 200000

int heap[nmax],hin[nmax],n,in[nmax],nr;

void add(int);
void del(int);
void showHeap();
void swap(int);
void filter(int);
void shift(int,int);

std::ifstream fin("heapuri.in");
std::ofstream fout("heapuri.out");

int main()
{
    int m,a,b;

    fin>>m;
    for(;m;m--)
    {
        fin>>a;
        if (a==1)
        {
            fin>>b;
            add(b);
        }
        else
        if (a==2)
        {
            fin>>b;
            del(b);
        }
        else
            showHeap();
    }
    return 0;
}

void add(int a)
{
    heap[++n]=a;
    hin[n]=++nr;
    in[nr]=n;
    filter(n);
}

void del(int a)
{
    heap[in[a]]=heap[n];
    n--;
    swap(in[a]);
}

void showHeap()
{
    fout<<heap[1]<<'\n';
}

void swap(int k)
{
    int fiu=1;
    while (fiu)
    {
        fiu=0;
        if (2*k<=n)
        {
            fiu=2*k;
            if (2*k+1<=n && heap[2*k+1]<heap[2*k])
                fiu=2*k+1;
            if (heap[fiu]>heap[k]) fiu=0;
        }
        if (fiu)
        {
            shift(k,fiu);
            k=fiu;
        }
    }
}

void filter(int k)
{
    while (k>1 && heap[k]<heap[k/2])
    {
        shift(k,k/2);
        k=k/2;
    }
}

void shift(int x,int y)
{
    int aux=heap[x];
    heap[x]=heap[y];
    heap[y]=aux;

    aux=hin[x];
    hin[x]=hin[y];
    hin[y]=aux;

    aux=in[hin[x]];
    in[hin[x]]=in[hin[y]];
    in[hin[y]]=aux;
}