Cod sursa(job #2266032)

Utilizator david.sachelarieDavid Sachelarie david.sachelarie Data 22 octombrie 2018 09:20:21
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int heap[200001];
vector <int> v;

void swapHeap(int a,int b){
    int aux;
    aux=heap[a];
    heap[a]=heap[b];
    heap[b]=aux;
}

void upHeap(int poz,int m){
    while(poz>=1 && heap[poz/2]>heap[poz]){
        swapHeap(poz/2,poz);
        poz/=2;
    }
}

int searchHeap(int val,int m){
    int i=m;
    while(heap[i]>val && i>=1) i/=2;
    while(i<=m && heap[i]!=val) i++;
    return i;
}

void downHeap(int poz,int m){
    int flag=0,poz_swap;
    while(flag==0){
        poz_swap=0;
        if(poz*2<=m && heap[2*poz]<heap[poz]) poz_swap=2*poz;;
        if(poz*2+1<=m && heap[2*poz+1]<heap[poz] && heap[2*poz+1]<heap[2*poz]) poz_swap=2*poz+1;

        if(poz_swap==0) flag=1;
        else{
            swapHeap(poz_swap,poz);
            poz=poz_swap;
        }
    }
}

int main()
{
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");

    int n;
    fin>>n;

    int i,m=0,operation,val,poz;
    for(i=0;i<n;i++){
        fin>>operation;
        if(operation!=3) fin>>val;
        if(operation==1){
            m++;
            v.push_back(val);
            heap[m]=val;
            upHeap(m,m);
        }
        else if(operation==2){
            poz=searchHeap(v[val-1],m);
            heap[poz]=heap[m];
            m--;
            downHeap(poz,m);
        }
        else{
            fout<<heap[1]<<endl;
        }
    }
    return 0;
}