Cod sursa(job #1053370)

Utilizator PsychoAlexAlexandru Buicescu PsychoAlex Data 12 decembrie 2013 18:26:26
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <fstream>
#include <vector>
//#include <map>
#include <unordered_map>

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

int n;
std::vector<int> heapu;
//std::map<int, int> hashu;
std::unordered_map<int, int> hashu;
std::vector<int> moFoPos;

void insertu(int val)
{
    heapu.push_back(val);
    int i = heapu.size() / 2;
    int j = heapu.size() - 1;

    hashu[val] = j;

    while(i >= 1 && heapu[i] > val)
    {
        hashu[heapu[i]] = j;
        hashu[heapu[j]] = i;

        int aux = heapu[i];
        heapu[i] = heapu[j];
        heapu[j] = aux;

        j = i;
        i = i / 2;
    }
}

void delu(int position)
{
    int valInit = heapu.back();
    position--;

    heapu[hashu[moFoPos[position]]] = heapu.back();
    hashu[heapu.back()] = hashu[moFoPos[position]];

    heapu.pop_back();

    int i = hashu[moFoPos[position]];
    while(i * 2 < heapu.size())
    {
        int val = heapu[i*2];
        int p = 0;

        if(i*2 + 1 < heapu.size() && heapu[i*2+1] < heapu[i*2])
        {
            val = heapu[i*2+1];
            p = 1;
        }

        if(valInit > heapu[i*2+p])
        {
            int a1 = hashu[heapu[i]], a2 = hashu[heapu[i*2+p]];
            int aux = heapu[i];

            hashu[heapu[i]] = a2;
            hashu[heapu[i*2 + p]] = a1;

            heapu[i] = heapu[i*2 + p];
            heapu[i*2 + p] = aux;
        }
        else
        {
            break;
        }
        i = i * 2 + p;
    }
}

void citirea()
{
    int x, y;
    fin>>n;
    for(int i = 0; i < n; i++)
    {
        fin>>x;
        if(x == 1)
        {
            fin>>y;
            moFoPos.push_back(y);
            insertu(y);
        }
        else
            if(x == 2)
            {
                fin>>y;
                delu(y);
            }
            else
                if(x == 3)
                {
                    fout<<heapu[1]<<'\n';
                }
    }
}

int main()
{
    heapu.push_back(-1);
    citirea();
    return 0;
}