Cod sursa(job #2909700)

Utilizator Alex_HossuHossu Alexandru Alex_Hossu Data 14 iunie 2022 19:34:24
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <stdio.h>
#include <algorithm>
using namespace std;

#define INSERT 1
#define DELETE 2
#define QUERY 3

#define MAX_N 100000

class Pair {
  public:
    int first;
    int second;
};

Pair heap[MAX_N + 1];
int heapSize;
bool erased[MAX_N];
int poz;
void addHeap(int val) {
    int i;
    heap[heapSize++] = {val, poz};
    poz++;
    i = heapSize - 1;
    while(i && heap[i].first < heap[(i - 1) / 2].first)  {
        swap(heap[i], heap[(i - 1) / 2]);
        i = (i - 1) / 2;
    }
}

void downHeap(int i) {
    int l, r, minn;

    l = 2 * i + 1;
    r = 2 * i + 2;
    minn = i;
    if(l < heapSize && heap[l].first < heap[minn].first)
        minn = l;
    if(r < heapSize && heap[r].first < heap[minn].first)
        minn = r;
    if(i != minn) {
        swap(heap[i], heap[minn]);
        downHeap(minn);
    }
}
void remove() {
    // int minn = heap[0].first;
    heap[0] = heap[--heapSize];
    downHeap(0);
    //return minn;
}

static inline int minimum() {
    return heap[0].first;
}

int main() {
  FILE *fin, *fout;
    int n, op, x, i;

    fin = fopen("heapuri.in", "r");
    fout = fopen("heapuri.out", "w");

    fscanf(fin, "%d", &n);
    poz = 0;
    for(i = 0; i < n; i++) {
        fscanf(fin, "%d", &op);
        switch (op) {
        case INSERT:
            fscanf(fin, "%d", &x);
            addHeap(x);
            break;
        case DELETE:
            fscanf(fin, "%d", &x);
            erased[x - 1] = true;
            break;
        case QUERY:
            while(erased[heap[0].second])
                remove();
            fprintf(fout, "%d\n", minimum());
            break;
        }
    }

    fclose(fin);
    fclose(fout);

    return 0;
}