Cod sursa(job #2419979)

Utilizator stefanpiturStefan Alexandru Pitur stefanpitur Data 9 mai 2019 23:25:58
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
/// Heap de mana

#include <iostream>
#include <cstdio>
using namespace std;
const int NMAX = 200001;
int H[NMAX][2];
int father(int nod){
    return nod/2;
}
int left_son(int nod){
    return 2*nod;
}
int right_son(int nod){
    return 2*nod + 1;
}
int nod[NMAX];
void sift(int length, int k){
    int son;
    do{
        son = 0;
        if(left_son(k) <= length && H[left_son(k)][0] < H[k][0]){
            son = left_son(k);
            if(right_son(k) <= length && H[left_son(k)][0] > H[right_son(k)][0])
                son = right_son(k);
        }
        if(son){
            swap(nod[H[k][1]],nod[H[son][1]]);
            swap(H[k],H[son]);
            k = son;
        }
    }while(son);
}
void percolate(int length, int k){
    while(k > 1 && H[father(k)][0] > H[k][0]){
        swap(nod[H[k][1]], nod[H[father(k)][1]]);
        swap(H[k], H[father(k)]);
        k = father(k);
    }
}
void insert_heap(int &length, int x, int ord){
    length++;
    H[length][0] = x;
    H[length][1] = ord;
    nod[H[length][1]] = ord;
    percolate(length,length);
}
void erase_heap(int &length, int k){
    H[k][0] = H[length][0];
    length --;
    if(k > 1 && H[k][0] < H[father(k)][0])
        percolate(length, k);
    else
        sift(length,k);
}
int main()
{
    FILE *fin, *fout;
    int n,tip,x,i,length=0,ord=0;
    fin=fopen("heapuri.in","r");
    fout=fopen("heapuri.out","w");
    fscanf(fin,"%d",&n);
    for(i=1;i<=n;i++){
        fscanf(fin,"%d",&tip);
        if(tip == 1){
            ord ++;
            fscanf(fin,"%d",&x);
            insert_heap(length,x,ord);
        }
        else if(tip == 2){
            fscanf(fin,"%d",&x);
            erase_heap(length,nod[x]);
        }
        else
            fprintf(fout,"%d\n",H[1][0]);
    }
    fclose(fin);
    fclose(fout);
    return 0;
}