Cod sursa(job #516429)

Utilizator dicu_dariaDaria Dicu dicu_daria Data 24 decembrie 2010 00:32:27
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 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 x=0;
	while (x!=i)
	{
		x=i;
		if (x*2<=h and a[heap[i]]>a[heap[x*2]]) i=x*2;
		if (x*2+1<=h and a[heap[i]]>a[heap[x*2+1]]) i=x*2+1;

		swap(heap[x],heap[i]);

		poz[heap[i]] = i;
        poz[heap[x]] = x;
	}

}
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]);
            poz[heap[poz[x]]]=poz[x];
            h--;
            heapify(poz[x]);
        }
        if(tip==3)
        fo<<a[heap[1]]<<"\n";
    }
    return 0;
}