Cod sursa(job #790493)

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

#include <iostream>
#include <fstream>


#define MAXN 200010
using namespace std;

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

void up(int i){
    if(i == 1) return;
    if(A[Heap[i/2]] > A[Heap[i]]){
        swap(Pos[Heap[i]], Pos[Heap[i/2]]);
        swap(Heap[i], Heap[i/2]);
        up(i/2);
    }
}

void down(int i){
    int min = i;
    int dr = 2*i;
    int st = 2*i+1;
    if(st <= heapSize && A[Heap[st]] < A[Heap[min]])
        min = st;
    if(dr <= heapSize && A[Heap[dr]] < A[Heap[min]])
        min = dr;
    if(i == min) return;
    swap(Pos[Heap[i]], Pos[Heap[min]]);
    swap(Heap[i], Heap[min]);
    down(min);
}

void push(int x){
    ++heapSize;
    ++posSize;
    A[posSize] = x;
    Pos[posSize] = heapSize;
    Heap[heapSize] = posSize;
    up(heapSize);
}

void pop(int x){
    int i = Pos[x];
    Pos[Heap[heapSize]] = Pos[Heap[i]];
    Heap[i] = Heap[heapSize];
    heapSize--;
    int nod = Pos[Heap[i]];
    if(nod > 1 && A[Heap[nod]] < A[Heap[nod/2]]){
        up(nod);
    }
    else
        down(nod);
}

int main()
{
    int op, x;
//    freopen("heapuri.in", "r", stdin);
//    freopen("heapuri.out", "w", stdout);
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f >> n;
    for(int i = 1; i <= n; i++){
        f >> op;
        if(op == 1){
            f >> x;
            push(x);
        }
        else if (op == 2){
            f >> x;
            pop(x);
        }
        else {
            g << A[Heap[1]] << endl;
        }
        
    }
    f.close();
    g.close();
    return 0;
}