Cod sursa(job #789093)

Utilizator ioana.teocIoana Teoc ioana.teoc Data 16 septembrie 2012 19:09:15
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
//
//  main.cpp
//  Heapuri
//
//  Created by Ioana Teoc on 9/16/12.
//  Copyright (c) 2012 Ioana Teoc. All rights reserved.
//

#include <iostream>
#include <stdio.h>

#define MAXN 200010
using namespace std;

int Heap[MAXN], Pos[MAXN], A[MAXN];
int n, heapSize, posSize;

void push(int x){
    int i = ++heapSize;
    while(i > 1 && Heap[i/2] > x){
        Heap[i] = Heap[i/2];
        Pos[A[i/2]] = i;
        A[i] = A[i/2];
        i = i/2;
    }
    Heap[i] = x;
    Pos[++posSize] = i;
    A[i] = posSize;
}

void pop(int x){
    int i = Pos[x];
    Heap[i] = Heap[heapSize];
    A[i] = A[heapSize--];
    Pos[A[i]] = i;
    
    int min, aux;
    while(2*i <= heapSize){
        if(2*i <= heapSize && Heap[2*i] < Heap[i])
            min = 2*i;
        else
            min = i;
        if(2*i+1 <= heapSize && Heap[2*i+1] < Heap[min])
            min = 2*i + 1;
        if(min == i)
            break;
        else{
            aux = Heap[min];
            Heap[min] = Heap[i];
            Heap[i] = aux;
            aux = Pos[A[i]];
            Pos[A[i]] = Pos[A[min]];
            Pos[A[min]] = aux;
            aux = A[i];
            A[i] = A[min];
            A[min] = aux;
        }

    }
}

int main(int argc, const char * argv[])
{
    int op, x;
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    cin >>n;
    for(int i = 1; i <= n; i++){
        cin >> op;
        if(op == 1){
            cin >> x;
            push(x);
        }
        else if (op == 2){
            cin >> x;
            pop(x);
        }
        else if(op == 3){
            cout << Heap[1] << endl;
        }
            
    }
    
    
}