Cod sursa(job #3233563)

Utilizator Vlad.Vlad Cristian Vlad. Data 3 iunie 2024 20:09:39
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <iostream>
#include <climits>

#define NMAX 200005

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");


struct nod {;
    int value, ord;
};

nod heap[NMAX];
int N = 0, cnt = 0;
int heappos[NMAX];

void demote(int pos) {
    int ls = 2 * pos, rs = ls + 1;
    int smaller = pos;
    if (ls <= N && heap[ls].value < heap[smaller].value) {
        smaller = ls;
    }
    if (rs <= N && heap[rs].value < heap[smaller].value) {
        smaller = rs;
    }
    if (smaller != pos) {
        swap(heap[smaller], heap[pos]);
        swap(heappos[heap[smaller].ord], heappos[heap[pos].ord]);
        demote(smaller);
    }
}

void promote(int pos) {
    int parent = pos / 2;
    if (parent == 0 || heap[parent].value < heap[pos].value) {
        return;
    }
    swap(heap[parent], heap[pos]);
    swap(heappos[heap[parent].ord], heappos[heap[pos].ord]);
    promote(parent);
}


void add(int value) {
    heap[++N].value = value;
    heap[N].ord = ++cnt;
    heappos[cnt] = N;
    promote(N);
}

void remov(int pos) {
    heap[pos].value = INT_MIN;
    promote(pos);
    swap(heap[1], heap[N]);
    swap(heappos[heap[1].ord], heappos[heap[N].ord]);
    N--;
    demote(1);
}

int get_min() {
    return heap[1].value;
}

int main()
{
    int Q, tip, val;
    fin >> Q;
    while (Q--) {
        fin >> tip;
        if (tip == 3) {
            fout << get_min() << "\n";
        }
        else if (tip == 2){
            fin >> val;
            remov(heappos[val]);
        }
        else {
            fin >> val;
            add(val);
        }
    }
    return 0;
}