Cod sursa(job #2322063)

Utilizator Alex.PAlexandru Pacurar Alex.P Data 17 ianuarie 2019 11:38:22
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <stdio.h>
#include <stdlib.h>
#define maxn 200001

using namespace std;

typedef int heap[maxn];

int poz[maxn];
int x=1;

inline int father(int nod){
    return nod/2;
}

inline int leftson(int nod){
    return nod*2;
}

inline int rightson(int nod){
    return nod*2+1;
}

inline int minim(heap H){
    return H[1];
}

void demote(heap H, int N, int K){
    int son=1;
    while(son){
        son=0;

        if(leftson(K)<=N){
            son=leftson(K);

            if(rightson(K)<=N && rightson(K)<H[son])
                son=rightson(K);

            if(H[son]>H[K])
                son=0;
        }

        if(son){
            int aux=H[K];
            H[K]=H[son];
            H[son]=aux;

            aux=poz[K];
            poz[K]=poz[son];
            poz[son]=aux;

            K=son;
        }
    }
}

void promote(heap H, int N, int K){
    int key=H[K];
    int startpoz=poz[K];

    while(K>1 && key<H[father(K)]){
        H[K]=H[father(K)];
        poz[father(K)]=K;
        K=father(K);
    }

    H[K]=key;
    poz[startpoz]=K;
}

void cut(heap H, int &N, int K){
    H[K]=H[N];
    N--;

    if(K>1 && H[K]<H[father(K)])
        promote(H,N,K);
    else
        demote(H,N,K);
}

void ins(heap H, int &N, int key){
    N++;
    H[N]=key;
    poz[x]=N;
    x++;
    promote(H,N,N);
}

int main()
{
    FILE *fin, *fout;
    int n,i,t,p,hsize;
    heap H;
    fin=fopen("heapuri.in","r");
    fout=fopen("heapuri.out","w");
    fscanf(fin,"%d",&n);
    hsize=0;
    for(n;n>0;n--){
        fscanf(fin,"%d",&t);
        if(t==1){
            fscanf(fin,"%d",&i);
            ins(H,hsize,i);
        }else if(t==2){
            fscanf(fin,"%d",&p);
            cut(H,hsize,poz[p]);
        }else
            fprintf(fout,"%d\n",minim(H));
    }
    return 0;
}