Cod sursa(job #3129407)

Utilizator RealDream21Fabian-Andrei RealDream21 Data 14 mai 2023 13:16:31
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

void pushHeap(vector<int>&v, int toPush);
void popHeap(vector<int>& v, int toPop);
int top(vector<int>& v);

int main()
{
    vector<int> push_history;
    push_history.push_back(-1);
    vector<int> v;
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int n;
    fin >> n;
    int operatie;
    for(int i = 0; i < n; i++){
        fin >> operatie;
        if(operatie == 1){
            int x;
            fin >> x;
            push_history.push_back(x);
            pushHeap(v, x);
        }
        else if(operatie == 2){
            int x;
            fin >> x;
            popHeap(v, push_history[x]);
        }
        else if(operatie == 3){
            fout << top(v) << endl;
        }
    }
    return 0;
}

void pushHeap(vector<int>& v, int toPush)
{
    v.push_back(toPush);
    int pos = v.size() - 1;
    while(pos){
        int tata = (pos - 1)/2;
        if(v[tata] > v[pos]){
            swap(v[tata], v[pos]);
            pos = tata;
        }
        else break;
    }
}

void popHeap(vector<int>& v, int toPop)
{
    int pos;
    for (int i = 0; i < v.size(); i++) {
        if (toPop == v[i]) {
            pos = i;
            break;
        }
    }
    if (pos == v.size() - 1) {
        v.pop_back();
        return;
    }
    swap(v[pos], v[v.size() - 1]);
    v.pop_back();
    while (pos * 2 < v.size()) {
        int st = pos * 2;
        int dr = pos * 2 + 1;
        if (dr < v.size() && v[dr] < v[st] && v[pos] > v[dr]) {
            swap(v[pos], v[dr]);
            pos = dr;
        } else if (v[pos] > v[st]) {
            swap(v[pos], v[st]);
            pos = st;
        } else {
            break;
        }
    }
}


int top(vector<int>& v)
{
    return v[0];
}