Cod sursa(job #516427)

Utilizator dicu_dariaDaria Dicu dicu_daria Data 24 decembrie 2010 00:00:04
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <algorithm>
using namespace std;
int a[200005],heap[200005],poz[200005],h,n;
int adauga(int i,int key)
{
    while(i>1 and a[heap[i/2]]>a[key])
    {
        heap[i]=heap[i/2];
        poz[i/2]=i;
        i=i/2;
    }
    heap[i]=key;
    poz[key]=i;
}
void heapify(int i)
{
    int left,right,smallest;
    left=2*i;
    right=2*i+1;
    smallest=i;
    if(left<=h and a[heap[left]]<a[heap[i]]) smallest=left;
    if(right<=h and a[heap[right]]<a[heap[smallest]]) smallest=right;
    if(smallest!=i) {
                     swap(poz[heap[i]],poz[heap[smallest]]);
                     swap(heap[i],heap[smallest]);
                     heapify(smallest);
                     }


}
int main()
{
    int tip,t,x;
    ifstream fi("heapuri.in");
    ofstream fo("heapuri.out");
    fi>>t;
    while(t--)
    {
        fi>>tip;
        if(tip<3) fi>>x;
        if(tip==1) //adauga in heap element x
        {
            a[++n]=x;
            heap[++h]=n;
            adauga(h,n);
        }
        if(tip==2) //sterge al x-lea element din heap
        {
            swap(heap[poz[x]],heap[h]);
            h--;
            heapify(poz[x]);
        }
        if(tip==3) fo<<a[heap[1]]<<"\n";
    }
    return 0;
}