Cod sursa(job #3131243)

Utilizator FlaviaF7Fota Stefania-Flavia FlaviaF7 Data 19 mai 2023 16:47:36
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

ifstream in("heapuri.in");
ofstream out("heapuri.out");

void repairHeapDown(vector<pair<int, int>>& heap, vector<int>& pos, int i) {
    int n = heap.size() - 1;
    while (2 * i <= n) {
        int j = 2 * i;
        if (j + 1 <= n && heap[j + 1].first < heap[j].first) {
            j++;
        }
        if (heap[j].first < heap[i].first) {
            swap(pos[heap[j].second], pos[heap[i].second]);
            swap(heap[j], heap[i]);
            i = j;
        } else {
            break;
        }
    }
}


void repairHeapUp(vector<pair<int, int>>& heap, vector<int>& pos, int i) {
    while (i > 1 && heap[i].first < heap[i / 2].first) {
        swap(heap[i], heap[i / 2]);
        swap(pos[heap[i].second], pos[heap[i / 2].second]);
        i /= 2;
    }
}

void insert(vector<pair<int, int>>& heap, vector<int>& pos, int x, vector<int>& elem) {
    int i = heap.size();
    heap.push_back(make_pair(x, i));
    pos.push_back(i);
    elem.push_back(x);
    pos[i] = i; // actualizăm poziția elementului în vectorul pos
    repairHeapUp(heap, pos, i);
}

void remove(vector<pair<int, int>>& heap, vector<int>& pos, int x, vector<int>& elem) {
    int i = pos[x];
    pos[heap[i].second] = pos[heap.back().second]; // actualizăm poziția elementului în vectorul pos
    swap(heap[i], heap.back());
    swap(pos[heap[i].second], pos[heap.back().second]);
    heap.pop_back();
    elem[heap[i].second] = heap[i].first; // actualizăm elementul în vectorul elem
    repairHeapDown(heap, pos, i);
}


int getMin(const vector<pair<int, int>>& heap) {
    return heap[1].first;
}

int main() {
    int n, a, b;
    in >> n;
    vector<pair<int, int>> heap(1); // utilizăm indexare de la 1
    vector<int> pos(n + 1, -1);
    vector<int> elem(1, 0); // utilizăm indexare de la 1

    for (int i = 0; i < n; i++) {
        in >> a;
        switch (a) {
            case 1: {
                in >> b;
                insert(heap, pos, b, elem);
                break;
            }
            case 2: {
                in >> b;
                remove(heap, pos, b, elem);
                break;
            }
            case 3: {
                out << getMin(heap) << '\n';
                break;
            }
            default:
                break;
        }
    }

    in.close();
    out.close();
    return 0;
}