Cod sursa(job #3233582)

Utilizator 21CalaDarius Calaianu 21Cala Data 3 iunie 2024 22:28:57
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.86 kb
#include <iostream>
#include <fstream>
#include <vector>

#define NMAX 200005

using namespace std;

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

int n,counter,N;
int pos[NMAX];
pair<int, int>  heap[NMAX];

void move_up(int index)
{
    int parinte = index / 2;
    if (parinte == 0 || heap[parinte].first < heap[index].first) {
        return;
    }
    swap(heap[parinte], heap[index]);
    swap(pos[heap[parinte].second], pos[heap[index].second]);
    move_up(parinte);
}

void move_down(int index)
{
    int ls = 2 * index, rs = ls + 1;
    int mini = index;
    if (ls <= N && heap[ls].first < heap[mini].first) {
        mini = ls;
    }
    if (rs <= N && heap[rs].first < heap[mini].first) {
        mini = rs;
    }
    if (mini != index) {
        swap(heap[mini], heap[index]);
        swap(pos[heap[mini].second], pos[heap[index].second]);
        move_down(mini);
    }
}

void insert(int x)
{
    heap[++N] = make_pair(x,++counter);
    pos[counter] = N;
    move_up(N);
}

void sterge(int index)
{
    /*if (heap.size() > 1)
    {
        int hsize = heap.size();
        cerr << "poz in heap : " << index << " " << heap[hsize - 1].second << " " << heap[index].second << '\n';
        
        heap[index] = heap[hsize - 1];
        cerr << "poz in heap : " << index << " " << heap[hsize - 1].second << " " << heap[index].second << '\n';
        pos[heap[hsize - 1].second] = index;
        //cerr << "marime1 : " << heap.size() << '\n';
        pos[heap[index].second] = -1;
        //pos[heap[hsize - 1].second] = index;
        //cerr << "marime2 : " << heap.size() << '\n';
        //cerr <<  pos.back() << " " <<  heap.back().first << ": back" << '\n';
        //pos[heap[index].second] = -1;
        heap.pop_back();
        //pos.pop_back();

        if (index > 0 && heap[index] < heap[index / 2])
        {
            move_up(index);
        }
        else {
            move_down(index);
        }
    }*/
    heap[index].first = INT_MIN;
    move_up(index);
    swap(heap[1], heap[N]);
    swap(pos[heap[1].second], pos[heap[N].second]);
    N--;
    move_down(1);
}

int minim() {
    return heap[1].first;
}

void afisare()
{
    for (int i = 1; i <= N; ++i)
    {
        cout << heap[i].first << " " << heap[i].second << "      ";
    }
    cout << '\n';
    for (int i = 1; i <= N; ++i)
    {
        cout << pos[i] << " ";
    }
    cout << '\n';
}

int main()
{
    fin >> n;
    while (n--)
    {
        int c;
        fin >> c;
        if (c == 1) {
            int x;
            fin >> x;
            insert(x);
        }
        else if (c == 2) {
            int x;
            fin >> x;
            sterge(pos[x]);
        }
        else {
            fout << minim() << '\n';
        }
        //afisare();
        //cout << n << " ";
    }
}