Cod sursa(job #2587285)

Utilizator WilIiamperWilliam Damian Balint WilIiamper Data 22 martie 2020 16:35:10
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>

using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");
int n, l, heap[200010], pozHeap[200010], indici[200010], p;

void inserare (int x) {
    heap[++l] = x;
    pozHeap[p] = l; indici[l] = p;
    int k = l;
    while (k > 1 && heap[k] < heap[k/2]) {
        swap(heap[k], heap[k/2]);
        pozHeap[ indici[k/2] ] = pozHeap[ indici[k] ];
        pozHeap[p] = k/2;
        swap(indici[k], indici[k/2]);
        k /= 2;
    }
}

void stergere (int poz) {
    swap( heap[poz], heap[l] );
    pozHeap[ indici[l] ] = poz;
    swap(indici[l], indici[poz]);
    l--;

    if ( poz > 1 && heap[poz] < heap[poz/2]) {
        while (poz > 1 && heap[poz] < heap[poz/2]) {
              swap(heap[poz], heap[poz/2]);
              swap(pozHeap[ indici[poz] ] , pozHeap[ indici[poz/2] ]);
              swap(indici[poz], indici[poz/2]);
              poz /= 2;
        }
    }
    else {

        while (poz < l) {
            int son = 0;
            if (2*poz <= l) {
                son = 2*poz;
                if (2*poz+1 <= l && heap[2*poz] > heap[2*poz+1]) son = 2*poz+1;
            }

            if (son) {
                swap(heap[poz], heap[son]);
                swap(pozHeap[ indici[poz] ], pozHeap[ indici[son] ]);
                swap(indici[poz], indici[son]);
                poz = son;
            }
            else break;
        }
    }
}

int main()
{
    int op, x;
    fin >> n;
    while (n--) {
        fin >> op;
        if (op < 3) fin >> x;

        if (op == 1) {
            p++;
            inserare(x);
        }
        else if (op == 2) {
            stergere( pozHeap[x] );
            pozHeap[x] = -1;
        }
        else if (op == 3) fout << heap[1] << "\n";
    }
    return 0;
}