Cod sursa(job #3124196)

Utilizator zzzzzZazaazaza zzzzz Data 27 aprilie 2023 11:08:11
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <algorithm>
#include <queue>

int n, c, x, j, k, heap[200005], poz[200005], v[200005];

void push(int p) {
    for(int hp = p >> 1; hp && v[heap[hp]] > v[heap[p]]; p = hp, hp /= 2) {
        std::swap(heap[hp], heap[p]);
        poz[heap[hp]] = hp;
        poz[heap[p]] = p;
    }
}

void pop(int x)
{
	for(int y = 0; x != y; )
	{
		y = x;

		if (y * 2 <= k && v[heap[x]] > v[heap[y * 2]]) x = y * 2;
		if (y * 2 + 1 <= k && v[heap[x]] > v[heap[y * 2 + 1]]) x = y * 2 + 1;

		std::swap(heap[x], heap[y]);
        poz[heap[x]] = x;
        poz[heap[y]] = y;
	}
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    scanf("%d", &n);
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &c);
        switch(c) {
            case 1: {
                scanf("%d", &x);
                v[++k] = x;
                heap[++j] = k;
                poz[k] = j;
                push(j);
                break;
            }
            case 2: {
                scanf("%d", &x);
                v[x] = -1;
                push(poz[x]);
                poz[heap[1]] = 0;
                heap[1] = heap[j--];
                poz[heap[1]] = 1;
                if (j > 1) pop(1);
                break;
            }
            case 3: printf("%d\n", v[heap[1]]);
        }
    }

    fclose(stdin);
    fclose(stdout);
    return 0;
}