Cod sursa(job #3130931)

Utilizator CiprianHutanuHutanu Ciprian CiprianHutanu Data 18 mai 2023 20:27:44
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 kb
#include <fstream>
#include <iostream>
#include <vector>

std::ifstream in;
std::ofstream out;


class heap{
public:
    std::vector<std::pair<int,int>> v;
    int a[200005];
    void descent(int);
    void rise(int);
    void insert(std::pair<int, int>);
    void pop(int);
    int top();
};

void heap::descent(int pos) {
    int aux;
    if (2 * pos + 1 >= v.size())
        return;
    if ((2 * pos + 2 == v.size()) or v[2 * pos + 1] < v[2 * pos + 2])
        if (v[2 * pos + 1].first < v[pos].first)
        {
            a[v[pos].second] = 2 * pos + 1;
            a[v[2 * pos + 1].second] = pos;
            std::pair<int,int> aux = v[2 * pos + 1];
            v[2 * pos + 1] = v[pos];
            v[pos] = aux;
            heap::descent(2 * pos + 1);
            return;
        }
        else
            return;
    else
    if (v[2 * pos + 2].first < v[pos].first)
    {
        a[v[pos].second] = 2 * pos + 2;
        a[v[2 * pos + 2].second] = pos;
        std::pair<int,int> aux = v[2 * pos + 2];
        v[2 * pos + 2] = v[pos];
        v[pos] = aux;
        heap::descent(2 * pos + 2);
        return;
    }
    else
        return;
}

void heap::rise(int pos) {
    while(pos){
        if(v[(pos - 1) / 2].first > v[pos].first){
            a[v[pos].second] = (pos - 1) / 2;
            a[v[(pos-1) / 2].second] = pos;
            std::pair<int,int> aux = v[(pos - 1) / 2];
            v[(pos - 1) / 2] = v[pos];
            v[pos] = aux;
            pos = (pos - 1) / 2;
        }
        else
            break;
    }
}

void heap::insert(std::pair<int, int> val) {
    v.push_back(val);
    a[val.second] = v.size()-1;
    heap::rise(v.size()-1);
}

void heap::pop(int pos) {
    pos = a[pos];
    v[pos] = v[v.size()-1];
    a[v[pos].second] = pos;
    v.pop_back();
    heap::descent(pos);
    heap::rise(pos);
}

int heap::top() {
    return v[0].first;
}



int main() {
    int n, i, op, x, m=0;
    heap h;

    in.open("heapuri.in");
    out.open("heapuri.out");

    in>>n;
    for(i = 0; i < n; i++){
        in>>op;
        if(op == 1){
            in >> x;
            std::pair<int,int> p(x, m);
            h.insert(p);
            m++;
        }
        else if(op==2){
            in >> x;
            h.pop(x-1);
        }
        else if(op == 3){
            out<<h.top()<<'\n';
        }
    }

    in.close();
    out.close();

    return 0;
}