Cod sursa(job #3130598)

Utilizator Serban09Baesu Serban Serban09 Data 18 mai 2023 03:08:42
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

vector<int> ordine;
int c = 1;

void push(vector<pair<int, int>> &h, int x)
{
    h.push_back(make_pair(x, c));
    c++;
    int i = h.size()-1;
    ordine.push_back(i);
    int aux = ordine.size()-1;
    while(i/2 && h[i].first < h[i/2].first){
        ordine[aux] = i/2;
        ordine[h[i/2].second] = i;
        swap(h[i], h[i/2]);
        i/=2;
    }

}

void delete_element(vector<pair<int, int>> &h, int n)
{

    int aux = h[h.size()-1].second;
    swap(h[ordine[n]], h[h.size()-1]);
    h.pop_back();
    ordine[aux] = ordine[n];
    int i=ordine[n];

    while((2*i < h.size() && h[i].first > h[2*i].first) || (2*i+1 < h.size() && h[i].first > h[2*i+1].first)){
        if(2*i+1 >= h.size() || h[2*i + 1].first > h[2*i].first){
            ordine[aux] = 2*i;
            ordine[h[2*i].second] = i;
            swap(h[i], h[2*i]);
            i *= 2;
        }
        else{
                ordine[aux] = 2*i+1;
                ordine[h[2*i+1].second] = i;
                swap(h[i], h[2*i+1]);
                i = 2*i + 1;
            }
    }
}

void extract_min(vector<pair<int, int>> &h)
{
    g<<h[1].first<<endl;
}

int main()
{
    ordine.push_back(-1);
    vector<pair<int, int>> h;
    h.push_back(make_pair(-1, -1));
    int n, x, y;
    f>>n;
    for(int i=0; i<n; i++){
        f>>x;
        switch(x)
        {
            case 1:{
                f>>y;
                push(h, y);
                break;
            }
            case 2:{
                f>>y;
                delete_element(h, y);
                break;
            }
            case 3:{
                extract_min(h);
                break;
            }
        }
//    for(int i=1; i<h.size(); i++)
//        cout<<h[i]<<" ";
//    cout<<endl;
//        for(int i=1; i<ordine.size(); i++)
//        cout<<ordine[i]<<" ";
//    cout<<endl<<endl;
    }

//    push(h, 3);
//    push(h, 4);
//    push(h, 1);
//    push(h, 2);
//    push(h, 6);
//    push(h, 5);
//    extract_min(h);
//    delete_element(h, 3);
//    extract_min(h);
//    delete_element(h, 2);

    return 0;
}