Cod sursa(job #2229970)

Utilizator vladm98Munteanu Vlad vladm98 Data 8 august 2018 17:01:48
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.43 kb
#include <bits/stdc++.h>

using namespace std;

int heap[200001];
int fromHeapToV[200001];
int fromVToHeap[200001];

void swapp (int firstPosition, int secondPosition) {
    swap (heap[firstPosition], heap[secondPosition]);
    int whereCurrent = fromHeapToV[firstPosition];
    int whereFather = fromHeapToV[secondPosition];
    fromVToHeap[whereCurrent] = secondPosition;
    fromVToHeap[whereFather] = firstPosition;
    swap (fromHeapToV[firstPosition], fromHeapToV[secondPosition]);
}

void insert (int value, int &heapSize, int &vSize) {
    heapSize += 1;
    vSize += 1;
    heap[heapSize] = value;
    fromHeapToV[heapSize] = vSize;
    fromVToHeap[vSize] = heapSize;

    int currentPosition = heapSize;
    while (currentPosition > 1 and heap[currentPosition] < heap[currentPosition / 2]) {
        swapp(currentPosition, currentPosition / 2);
        currentPosition /= 2;
    }
}

void erase (int vPosition, int &heapSize) {
    int currentPosition = fromVToHeap[vPosition];
    swapp(currentPosition, heapSize);
    heapSize -= 1;
    while (currentPosition > 1 and heap[currentPosition] < heap[currentPosition / 2]) {
        swapp(currentPosition, currentPosition / 2);
        currentPosition /= 2;
    }
    while (true) {
        int leftSon = currentPosition << 1;
        int rightSon = currentPosition << 1 | 1;
        if (leftSon > heapSize) break;
        if (rightSon > heapSize) {
            if (heap[currentPosition] > heap[leftSon]) {
                swapp(currentPosition, leftSon);
                currentPosition = leftSon;
            }
            else {
                break;
            }
        }
        else {
            if (heap[currentPosition] <= min (heap[leftSon], heap[rightSon])) break;
            int minSon = leftSon;
            if (heap[rightSon] < heap[leftSon]) minSon = rightSon;
            swapp(currentPosition, minSon);
            currentPosition = minSon;
        }
    }
}

int main()
{
    ifstream fin ("heapuri.in");
    ofstream fout ("heapuri.out");
    int q, heapSize = 0, vSize = 0;
    fin >> q;
    for (int i = 1; i <= q; ++i) {
        int type;
        fin >> type;
        if (type == 1) {
            int value;
            fin >> value;
            insert(value, heapSize, vSize);
        }
        if (type == 2) {
            int value;
            fin >> value;
            erase(value, heapSize);
        }
        if (type == 3) {
            fout << heap[1] << '\n';
        }
    }
    return 0;
}