Cod sursa(job #2893906)

Utilizator VartonVarts Var Varton Data 26 aprilie 2022 19:45:19
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream is("heapuri.in");
ofstream os("heapuri.out");
const int nrmax = 200005;
int poz[nrmax], ord, aux[nrmax], heap[nrmax], n, nr_op;
int mx, l, r, op, val, s1;

void heapify( int i){
    if(heap[(i-1) /2] > 0){
        if(heap[i]<heap[(i-1) /2]){
            swap(poz[ord], poz[aux[(i-1) /2]]);
            swap(heap[i], heap[(i-1) /2]);
            swap(aux[i], aux[(i-1) /2]);
            heapify((i-1)/2);
        }
    }
}

void heapifyTop(int i){
    mx = i;
    l = 2 * mx + 1;
    r = 2 * mx + 2;
    if(l<n && heap[l] < heap[mx])
        mx = l;
    if(r<n && heap[r]<heap[mx])
        mx = r;
    if(mx != i){
        swap(poz[aux[i]], poz[aux[mx]]);
        swap(heap[i], heap[mx]);
        swap(aux[i], aux[mx]);
        heapifyTop(mx);
    }

}

void inserare(int elem){

    heap[n-1] = elem;

    heapify(n-1);
}



void stergere(int k){
     s1 = poz[k];
    heap[poz[k]] =  heap[n-1];
    swap(poz[k], poz[aux[n-1]]);
    swap(aux[s1], aux[n-1]);
    n--;
    for(int i = 0; i<=2; i++)
        heapifyTop(i);
}



int main()
{
    is>>nr_op;

    for(int i =0; i<nr_op;i++){
        is>>op;
        if(op==3)
        {
            os<<heap[0];
            os<<endl;
        }

        if(op==1)
        {
            is>>val;
                ord++;
                n++;
                poz[ord] = n-1;
                aux[n-1] = ord;
            inserare(val);
        }
        if(op==2)
        {
            is>>val;
            stergere(val);
        }

    }
    return 0;
}