Cod sursa(job #1785884)

Utilizator OleaginoasaCristina Oleaginoasa Data 22 octombrie 2016 03:38:23
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

vector<long long int> heapVector;

void upheap(int pos){
    while((pos-1)/2 >= 0 && heapVector[(pos-1)/2] > heapVector[pos]){
        swap(heapVector[(pos-1)/2],heapVector[pos]);
        pos = (pos-1)/2;
    }
}

void downheap(int i){
    int pos = 0, size = heapVector.size();
    while( (2*i+1) < size && (2*i+2) < size && (heapVector[2*i+1] < heapVector[i] || heapVector[2*i+2] < heapVector[i])){
        if(heapVector[2*i+2] > heapVector[2*i+1])
            pos = 2*i+1;
        else
            pos = 2*i+2;

        swap(heapVector[i], heapVector[pos]);
        i = pos;
    }
}

void addElement(long long int x){
    heapVector.push_back(x);
    int pos = heapVector.size()-1;
    upheap(pos);
}

void deleteElement(long long int x){
    int i = 0, size = heapVector.size();

    while(i < size && heapVector[i] != x){
        i++;
    }
    //cout << "Sterge " << x << endl;
    heapVector[i] = heapVector[size-1];
    heapVector.erase(heapVector.begin() + size-1);
    
    if(i == 0 || heapVector[i] > heapVector[(i-1)/2])
        downheap(i);
    else
        upheap(i);
    }


long long int minElement(){
    return heapVector[0];
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int Q, type;
    vector<long long int> v;
    long long int number;
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out","w", stdout);
    
    scanf("%d", &Q);
    for(int i = 0; i < Q; ++i){
        scanf("%d", &type);
        if(type == 1){
            scanf("%lld", &number);
            addElement(number);
            v.push_back(number);
            
        }
        else if(type == 2){
            scanf("%lld", &number);
            deleteElement(v[number-1]);
        }
        else
            printf("%lld \n", minElement());
    }
    return 0;
}