Cod sursa(job #2615256)

Utilizator Tudor_PascaTudor Pasca Tudor_Pasca Data 13 mai 2020 22:37:47
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int T;
int heap[200010], n = 0;
int node[200010], i = 0;
int val[200010];

void printData()
{
    for(int i = 1; i <= n; i++)
        cout << heap[node[i]] << ' ' << node[i] << '\n';

    cout << '\n';
}

void heapUp(int x)
{
    int father = x / 2;

    while(father > 0)
    {
        if(heap[x] >= heap[father])
            return;

        swap(heap[x], heap[father]);
        swap(node[val[x]], node[val[father]]);
        swap(val[x], val[father]);

        x = x / 2;
        father = x / 2;
    }
}

void heapDown(int x)
{
    int child = x * 2;

    while(child <= n)
    {
        if(child + 1 <= n && heap[child] > heap[child + 1])
            child++;

        if(heap[child] < heap[x])
        {
            swap(heap[x], heap[child]);
            swap(node[val[x]], node[val[child]]);
            swap(val[x], val[child]);
        }

        x *= 2;
        child = x * 2;
    }
}

void heapInsert(int x)
{
    n++;
    i++;

    heap[n] = x;

    node[i] = n;
    val[n] = i;

    heapUp(n);
}

void heapDelete(int x)
{
    swap(heap[x], heap[n]);
    swap(node[val[x]], node[val[n]]);
    swap(val[x], val[n]);

    n--;

    heapUp(x);
    heapDown(x);
}

int heapMin()
{
    return heap[1];
}


int main()
{
    in >> T;

    while(T--)
    {
        int test, value;
        in >> test;

        switch(test)
        {
            case 1:
                in >> value;
                heapInsert(value);
                break;

            case 2:
                in >> value;
                heapDelete(node[value]);
                break;

            case 3:
                out << heapMin() << '\n';
        }
    }

    return 0;
}