Cod sursa(job #1138927)

Utilizator UAIC_Balan_Negrus_HreapcaUAIC Balan Negrus Hreapca UAIC_Balan_Negrus_Hreapca Data 10 martie 2014 18:54:36
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.79 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <random>
#include <assert.h>
using namespace std;

const string file = "heapuri";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f; 

//#define ONLINE_JUDGE

vector<int> heap;
vector<int> poz;
vector<int> elem;
int heapSize;

int lSon(int i)
{
    return i*2;
}
int rSon(int i)
{
    return i*2+1;
}
int parent(int i)
{
    return i/2;
}

void heapInit()
{
    heap.push_back(0);
}
void heapSwap(int a, int b)
{
    int aux = heap[a];
    heap[a] = heap[b];
    heap[b] = aux;
    poz[heap[a]] = a;
    poz[heap[b]] = b;
}

void heapUp(int i)
{
    while(i != 1 && elem[heap[i]] < elem[heap[parent(i)]])
    {
        heapSwap(i, parent(i));
        i = parent(i);
    }
}

void heapDown(int i)
{
    while(true)
    {
        int mini = i;
        if(lSon(i) <= heapSize && elem[heap[lSon(i)]] < elem[heap[mini]])
            mini = lSon(i);
        if(rSon(i) <= heapSize && elem[heap[rSon(i)]] < elem[heap[mini]])
            mini = rSon(i);
        if(mini == i)
            break;
        heapSwap(mini, i);
        i = mini;
    }
}

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

void heapInsert(int v)
{
    heap.push_back(v);
    heapSize++;
    poz[heap[heapSize]] = heapSize;
    heapUp(heapSize);
}
void heapPop()
{
    heapSwap(1, heapSize);
    heapSize--;
    heap.pop_back();
    heapDown(1);
}
void heapDelete(int i)
{
    elem[heap[i]] = -INF;
    heapUp(i);
    heapPop();
}

int main()
{
#ifdef ONLINE_JUDGE
	ostream &fout = cout;
	istream &fin = cin;
#else
	fstream fin(infile.c_str(), ios::in);
	fstream fout(outfile.c_str(), ios::out);
#endif	

    int N;
    fin >> N;
    int count = -1;
    heapInit();
    for(int i = 0; i < N; i++)
    {
        int op, x;
        fin >> op;
        if(op == 1)
        {
            fin >> x;
            count++;
            elem.push_back(x);
            poz.push_back(0);
            heapInsert(count);
        }
        else if(op == 2)
        {
            fin >> x;
            heapDelete(poz[x - 1]);
        }
        else if(op == 3)
        {
            fout << elem[heapTop()] << "\n";
        }
    }

#ifdef ONLINE_JUDGE
#else
    fout.close();
	fin.close();
#endif
}