Cod sursa(job #767395)

Utilizator test_666013Testez test_666013 Data 13 iulie 2012 14:22:16
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAX 200002

struct heap{ int x,i; }h[MAX];
int n,pos[MAX],k;

void add(int x,int i){
    k++;
    h[k].x = x;
    h[k].i = i;
    pos[i] = k;

    int f = k, t = f/2;

    while(t > 0 && h[t].x > h[f].x)
    {
        swap( pos[h[t].i],pos[h[f].i] );
        swap( h[t],h[f] );
        f = t; t = f/2;
    }
}

void remove(int i){
    int t = pos[i], f;
    h[t] = h[k];
    k--;

    f = 2*t;
    if( f+1 <= k && h[f+1].x < h[f].x )f++;

    while(f <= k && h[t].x > h[f].x)
    {
        swap( pos[h[t].i],pos[h[f].i] );
        swap( h[t],h[f] );
        t = f; f = 2 * t;
        if( f+1 <=k && h[f+1].x < h[f].x )f++;
    }
}

int main(){
    int c,x;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&c);
            switch(c){
                case 1: scanf("%d",&x); add(x,i); break;
                case 2: scanf("%d",&x); remove(x); break;
                case 3: printf("%d\n",h[1].x); break;
            }
        }
    return 0;
}