Cod sursa(job #2808943)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 25 noiembrie 2021 18:27:15
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

int heap[200000];
int v[200000];
int heap_size;

int parent(int n) {
    return (n - 1) / 2;
}

int left_child(int n) {
    return n * 2 + 1;
}

int right_child(int n) {
    return n * 2 + 2;
}

void upheap(int loc_in_heap) {
    while ( loc_in_heap > 0 && heap[parent(loc_in_heap)] > heap[loc_in_heap] ) {
        swap(heap[parent(loc_in_heap)], heap[loc_in_heap]);
        upheap(parent(loc_in_heap));
    }
}

void downheap(int loc_in_heap) {
    if ( left_child(loc_in_heap) < heap_size && heap[left_child(loc_in_heap)] < heap[loc_in_heap] ) {
        if ( right_child(loc_in_heap) >= heap_size || heap[left_child(loc_in_heap)] < heap[right_child(loc_in_heap)]) {
          swap(heap[left_child(loc_in_heap)], heap[loc_in_heap]);
          downheap(left_child(loc_in_heap));
        } else {
          swap(heap[right_child(loc_in_heap)], heap[loc_in_heap]);
          downheap(right_child(loc_in_heap));
        }
    }
}

void erase_min() {
  heap_size--;
  swap(heap[0], heap[heap_size]);
  downheap(0);
}

int get_min() {
  return heap[0];
}

void update(int pos, int value) {
  heap[pos] = value;
  upheap(pos);
  downheap(pos);
}

void erase_elem(int pos) {
  update(pos, get_min());
  erase_min();
}

int search_elem(int elem) {
    int i;

    i = 0;
    while ( heap[i] != elem ) {
      i++;
    }

    return i;
}

int main() {
    FILE *fin, *fout;
    fin = fopen("heapuri.in", "r");
    fout = fopen("heapuri.out", "w");

    int n, i, q, nr, pos_elem;

    fscanf(fin, "%d", &n);

    heap_size = 0;
    for ( i = 0; i < n; i++ ) {
        fscanf(fin, "%d", &q);
        if ( q == 1 ) {
            fscanf(fin, "%d", &nr);

            heap[heap_size] = nr;
            v[heap_size] = nr;

            upheap(heap_size);

            heap_size++;
        } else if ( q == 2 ) {
            fscanf(fin, "%d", &nr);
            nr--;

            pos_elem = search_elem(v[nr]);
            erase_elem(pos_elem);
        } else if ( q == 3 ) {
            fprintf(fout, "%d\n", heap[0]);
        }
    }
    return 0;
}