Cod sursa(job #790522)

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

#include <iostream>
#include <fstream>

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");
#define MAXN 200005

int Heap[MAXN], Pos[MAXN], V[MAXN], n, heapSize;

void citeste(){
    f>>n;
}
void up(int nod){
    if(nod == 1) return;
    if(V[Heap[nod]] < V[Heap[nod/2]]){
        swap(Pos[Heap[nod]], Pos[Heap[nod/2]]);
        swap(Heap[nod], Heap[nod/2]);
        up(nod/2);
    }
}

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

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

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

void rezolva(){
    int op, x;
    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 << V[Heap[1]] << endl;
        }
        
    }
    
}

int main()
{
    citeste();
    rezolva();
    f.close();
    g.close();
    return 0;
}