Cod sursa(job #2901343)

Utilizator VartonVarts Var Varton Data 13 mai 2022 16:51:27
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream is("heapuri.in");
ofstream os("heapuri.out");
#define 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]<heap[i /2] && i>1){
            swap(poz[ord], poz[aux[i /2]]);
            swap(heap[i], heap[i /2]);
            swap(aux[i], aux[i /2]);
            heapify(i/2);
        }

}

void heapifyTop(int i){
    mx = i;
    l = 2 * mx ;
    r = 2 * mx + 1;
    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] = elem;

    heapify(n);
}



void stergere(int k){
    s1 = poz[k];
    heap[poz[k]] =  heap[n];
    swap(poz[k], poz[aux[n]]);
    swap(aux[s1], aux[n]);
    n--;
    heapifyTop(s1);
}



int main()
{
    is>>nr_op;

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

        if(op==1)
        {
            is>>val;
            ord++;
            n++;
            poz[ord] = n;
            aux[n] = ord;
            inserare(val);
        }
        if(op==2)
        {
            is>>val;
            stergere(val);
        }
        for(int j=1; j<=n;j++)
            cout<<heap[j]<<" ";
        cout<<endl;

    }

    return 0;
}