Cod sursa(job #2770957)

Utilizator ana_madalina_18Radu Ana Madalina ana_madalina_18 Data 24 august 2021 13:03:15
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.45 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
struct Element
{
    int poz,valoare;
};
class Heap
{
    vector <Element> vec;
    vector <bool> sters;
    void pop()
    {
        swap(vec[1],vec.back());
        vec.pop_back();
        int pozitie=1;
        while(pozitie*2<vec.size())
        {
            int copilut,copil_stang=2*pozitie, copil_drept=2*pozitie+1;
            if(copil_drept>=vec.size())
            {
                copilut=copil_stang;
            }
            else if(vec[copil_stang].valoare<vec[copil_drept].valoare)
            {
                copilut=copil_stang;
            }
            else
            {
                copilut=copil_drept;
            }
            if(vec[pozitie].valoare>vec[copilut].valoare)
            {
                swap(vec[pozitie],vec[copilut]);
                pozitie=copilut;
            }
            else
            {
                break;
            }
        }
    }
public:
    Heap(int n)
    {
       Element x;
       x.poz=-1;
       x.valoare=-1000000000;
       vec.push_back(x);
       sters.resize(n+1);
    }
    void push(Element x)
    {
        vec.push_back(x);
        int curent=vec.size()-1;
        int parinte=curent/2;
        while(vec[curent].valoare<vec[parinte].valoare && parinte!=0)
        {
            swap(vec[curent],vec[parinte]);
            curent=parinte;
            parinte=curent/2;
        }
    }
    void pop(int pozitie)
    {
        sters[pozitie]=true;
    }
    int top()
    {
        /*for(bool curent: sters)
            cout<<curent<<' ';
        cout<<endl;
        cout<<vec[1].poz<<' '<<vec[1].valoare<<endl;*/
        while(sters[vec[1].poz]==true)
        {
            this->pop();
        }
        return vec[1].valoare;
    }
};
int main()
{
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int n;
    fin>>n;
    Heap heap(n);
    int op, pozitie=0, val;
    Element x;
    for(int i=1;i<=n;i++)
    {
       fin>>op;
       if(op==1)
       {
          fin>>val;
          Element x;
          pozitie++;
          x.poz=pozitie;
          x.valoare=val;
          heap.push(x);
       }
       else if(op==2)
       {
           int p;
           fin>>p;
           heap.pop(p);
       }
       else
       {
           fout<<heap.top()<<'\n';
       }
    }
    return 0;
}