Cod sursa(job #3123657)

Utilizator speedy_gonzalesDuca Ovidiu speedy_gonzales Data 25 aprilie 2023 07:29:16
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <iostream>
#include <vector>
#include <map>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <queue>
#include <cmath>
#include <set>
#include <unordered_map>
#include <stack>
#include <iomanip>

using namespace std;

ifstream fin("1.in");
ofstream fout("heapuri.out");

const int MAX = 200005;
bool deleted[MAX];
int cnt = 0;

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

int leftChild(int index) {
    return index * 2 + 1;
}

int rightChild(int index) {
    return index * 2 + 2;
}

void insert(vector<pair<int, int>> &heap, int value) {
    ++cnt;
    if ((int) heap.size() == 0) {
        heap.push_back({value, cnt});
        return;
    }
    heap.push_back({value, cnt});

    int child = (int) heap.size() - 1;
    int parentIndex = parent(child);

    while (child > 0 && heap[child].first < heap[parentIndex].first) {
        swap(heap[child], heap[parentIndex]);
        child = parentIndex;
        parentIndex = parent(child);
    }
}

void deleteValue(vector<pair<int, int>> &heap, int value) {
    int index = 0;

    swap(heap[index], heap[(int) heap.size() - 1]);
    heap.pop_back();

    while (index < (int) heap.size()) {
        int mini = heap[index].first;
        int nextIndex = index;
        if (leftChild(index) < (int) heap.size() && heap[leftChild(index)].first < mini) {
            mini = heap[leftChild(index)].first;
            nextIndex = leftChild(index);
        }
        if (rightChild(index) < (int) heap.size() && heap[rightChild(index)].first < mini) {
            mini = heap[rightChild(index)].first;
            nextIndex = rightChild(index);
        }

        if (nextIndex == index) {
            break;
        }
        swap(heap[index], heap[nextIndex]);
        index = nextIndex;
    }
}

int main() {
    int n;
    fin >> n;

    vector<pair<int, int>> heap;

    vector<int> pos(MAX);

    for (int i = 0; i < n; ++i) {
        int x, y;
        fin >> x;
        if (x == 1) {
            fin >> y;
            insert(heap, y);
        } else if (x == 3) {
            while (deleted[heap[0].second]) {
                deleteValue(heap, 1);
            }
            fout << heap[0].first << "\n";
//            fout << heap[0].first << "\n";
//            deleteValue(heap, pos[y]);

        } else if (x == 2) {
            fin >> y;
            deleted[y] = true;
        }
    }

    return 0;
}