Cod sursa(job #2815202)

Utilizator cezar.balutaCezar Baluta cezar.baluta Data 9 decembrie 2021 11:53:16
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

vector<int>heap(1,0);
vector<int>ordine(1,0);
vector<int>indice(1,0);
int cnt=1;

void up(int poz){
    while(heap[poz]<heap[poz/2] && poz>1){
           // cout<<"pozitie "<<poz<<"\n";

        swap(heap[poz],heap[poz/2]);
        swap(ordine[indice[poz]],ordine[indice[poz/2]]);
        swap(indice[poz],indice[poz/2]);
        poz/=2;
    }
}

void down(int poz){
    int l = heap.size();
    while(poz*2 < l){
        int fiu = 2*poz;
        fiu+=(l>fiu+1 && heap[fiu]>heap[fiu+1]);
        if(heap[fiu]>=heap[poz])
            break;
        swap(heap[poz],heap[fiu]);
        swap(ordine[indice[poz]],ordine[indice[fiu]]);
        swap(indice[poz],indice[fiu]);
        poz=fiu;
    }
}

void ins(int x){
    heap.push_back(x);
    indice.push_back(cnt);
    cnt++;
    ordine.push_back(heap.size()-1);
    int poz=heap.size()-1;
    if( poz>1  && heap[poz]<heap[poz/2] )
        up(poz);
}

void del(int poz){
   // cout<<1;

    swap(heap[heap.size()-1],heap[poz]);
   // cout<<2;
    swap(ordine[indice[poz]],ordine[indice[indice.size()-1]]);
   // cout<<3;
    swap(indice[poz],indice[indice.size()-1]);
    heap.pop_back();

    up(poz);

    down(poz);
}

int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    int n,cerinta,x;
    in>>n;
    for(int i=0;i<n;i++){
        in>>cerinta;
        if(cerinta == 1){
            in>>x;
            ins(x);

        }
        else if(cerinta == 2){
            in>>x;
            del(ordine[x]);

        }
        else{
            out<<heap[1]<<'\n';
        }
    }


    return 0;
}