Cod sursa(job #348377)

Utilizator csizMocanu Calin csiz Data 15 septembrie 2009 18:00:08
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <vector>
#include <fstream>
#include <iostream>

std::vector<int> heap;
std::vector<int> v;
std::vector<int> pos;


int parent(int n){
    return n/2;
}
int first(int n){
    return 2*n;
}
int second(int n){
    return 2*n+1;
}

bool comp(int f,int s){
    return v[heap[f]]<v[heap[s]];
}
void swap(int f,int s){
    std::swap(heap[f],heap[s]);
    pos[heap[f]]=f;
    pos[heap[s]]=s;
}

void insert(int k){
    int n=heap.size();
    v.push_back(k);
    heap.push_back(pos.size());
    pos.push_back(n);
    while(parent(n)&&comp(n,parent(n))) swap(n,parent(n));
}
int max(){
    return v[heap[1]];
}
void del(int k){
    int n=pos[k];
    swap(n,heap.size()-1);
    heap.pop_back();
    while(parent(n)&&comp(n,parent(n))) swap(n,parent(n));
    bool go=true;
    while(go){
        go=false;
        if(second(n)<heap.size()){
            if(comp(second(n),n)){
                if(comp(first(n),second(n))){
                    swap(first(n),n);go=true;n=first(n);
                }else{
                    swap(second(n),n);go=true;n=second(n);
                }
            }else if(comp(first(n),n)){
                swap(first(n),n);go=true;n=first(n);
            }
        }
    }
    if(first(n)<heap.size()){
        if(comp(first(n),n)){
            swap(first(n),n);go=true;n=first(n);
        }
    }
}


int main(){
    std::ifstream in("heapuri.in");
    std::ofstream out("heapuri.out");
    int n;in>>n;
    heap.push_back(0);heap.reserve(n+1);
    v.push_back(0);v.reserve(n+1);
    pos.push_back(0);pos.reserve(n+1);

    for(int i=0;i<n;++i){
        int c;in>>c;
        switch(c){
            case 1:{
                int x;in>>x;insert(x);break;
            }
            case 2:{
                int x;in>>x;del(x);break;
            }
            case 3:{
                out<<max()<<"\n";break;
            }
        }
    }
}