Cod sursa(job #1482276)

Utilizator dorumusuroiFMI - Doru Musuroi dorumusuroi Data 6 septembrie 2015 19:46:57
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <iostream>
using namespace std;

const char iname[] = "heapuri.in";
const char oname[] = "heapuri.out";
const int MAXN = 200005;

int n, a[MAXN], heap[MAXN], pos[MAXN], NR=0, L=0;

void upheap(int poz){
    while((poz > 1) && (a[heap[poz/2]] >= a[heap[poz]]))
    {
        swap(pos[heap[poz]], pos[heap[poz/2]]);
        swap(heap[poz], heap[poz/2]);
        poz /= 2;
    }
}
void downheap(int poz){
    while((2*poz+1 <= NR && (a[heap[poz]] >= a[heap[poz*2]]))|| (2*poz <= NR &&(a[heap[poz]] >= a[heap[poz*2+1]]))){
        if(2*poz+1 > NR  || a[heap[poz*2]]<a[heap[poz*2+1]]){
            swap(pos[heap[poz]], pos[heap[poz*2]]);
            swap(heap[poz], heap[poz*2]);
            poz *= 2;
        }
        else{
            swap(pos[heap[poz]], pos[heap[poz*2+1]]);
            swap(heap[poz], heap[poz*2+1]);
            poz = poz*2+1;
        }
    }
}
void read(){
    ifstream f(iname);
    ofstream g(oname);
    f >> n;
    for(int i = 1; i <= n; ++i){
        int c;
        f >> c;
        if(c == 1){
            L++;
            NR++;
            f >> a[L];
            heap[NR] = L;
            pos[L] = NR;
            upheap(NR);
        }
        else if(c == 2){
            int position;
            f >> position;
            heap[pos[position]] = heap[NR];
            pos[heap[NR]] = pos[position];
            NR--;
            downheap(pos[position]);
        }
        if(c==3){
            g << a[heap[1]] << '\n';
        }
    }
}

int main()
{
    read();
    return 0;
}