Cod sursa(job #2887470)

Utilizator DragosG12Ghinea Dragos DragosG12 Data 9 aprilie 2022 18:18:46
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include<fstream>
using namespace std;

int heap[200005], cronologic[200005];
int backHeap=1;
int n;

void inserare(int x){
    heap[backHeap]=x;
    int poz=backHeap;
    backHeap++;

    while(poz!=1 && heap[poz]<heap[poz/2]){
        swap(heap[poz], heap[poz/2]);
        poz/=2;
    }
}

void stergeRoot(){
    backHeap--;
    swap(heap[1], heap[backHeap]);
    int poz=1;


    while(1){
        if(2*poz>=backHeap)
            break;

        if(2*poz+1>=backHeap){
            if(heap[poz]>heap[2*poz])
                swap(heap[poz], heap[2*poz]);
            break;
        }

        if(heap[2*poz]<heap[2*poz+1]){
            if(heap[poz]<heap[2*poz])
                break;
            swap(heap[poz], heap[2*poz]);
            poz*=2;
        }
        else{
            if(heap[poz]<heap[2*poz+1])
                break;
            swap(heap[poz], heap[2*poz+1]);
            poz=2*poz+1;

        }
    }
}

void stergere(int x){
    int poz=1;
    for(int i=1;i<=backHeap;i++)
        if(heap[i]==x){
                poz=i;
                break;
        }

    while(poz!=1){
        swap(heap[poz], heap[poz/2]);
        poz/=2;
    }

    stergeRoot();
}

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

    fin>>n;
    int optiune;
    int contor=1;
    for(int i=0;i<n;i++){
        fin>>optiune;
        //inserare
        if(optiune==1){
            int x;
            fin>>x;
            inserare(x);
            cronologic[contor++]=x;
        }
        //stergere
        else if(optiune==2){
            int poz;
            fin>>poz;
            stergere(cronologic[poz]);
        }
        //minim
        else{
            fout<<heap[1]<<"\n";
        }
    }



    fout.close();
    fin.close();

    return 0;
}