Cod sursa(job #738556)

Utilizator RobertBBadea Corneliu Robert RobertB Data 20 aprilie 2012 20:36:29
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
using namespace std;

unsigned int Nr;
map<int,int> nr_ap;
vector<int> H;
vector<int> poz;

inline int father(int x)
{
	return x/2;
}
inline int left(int x)
{
	return x*2;
}
inline int right(int x)
{
	return x*2 + 1;
}

void sift(int N, int k)
{
	int son;
	do{
		son = 0;
		if(left(k) <= N) {
			son = left(k);
			if(right(k) <= N && H[left(k)] > H[right(k)]) {
				son = right(k);
			}
			if(H[k] <= H[son]) {
				son = 0;
			}
		}
		if(son) {
			swap(H[k], H[son]);
			k = son;
		}
	}while(son);
}

void perc(int N, int k) 
{
	int key = H[k];
	while (k > 1 && key < H[father(k)]) {
		H[k] = H[father(k)];
		k = father(k);
	} 
	H[k] = key;
}

void cut(int& N, int k) {
    H[k] = H[N];
    --N;
	H.pop_back();
    if (k > 1 && H[k] < H[father(k)]) {
        perc(N, k);
    } else {
        sift(N, k);
    }
}

void insert(int& N, int elem)
{
	H.push_back(elem);
	perc(N, N);
}

void rad(int& N)
{
	H[1] = H[N--];
	H.pop_back();
	sift(N, 1);
}

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

int main()
{
	H.push_back(0);
	poz.push_back(0);
	int cod, x;
	int i,j;
	int L = 0;
	f>>Nr;
	for(i = 1; i <= Nr; i++) {
		f>>cod;
		switch(cod) {
			case 1:
				f>>x;
				nr_ap[x]++; 
				L++;
				insert(L, x);
				poz.push_back(x);
				break;
			case 2:
				f>>x;
				nr_ap[poz[x]]--;
				break;
			case 3:
				while(nr_ap[H[1]] == 0){
					rad(L);
				}
				g<<H[1]<<endl;
				break;
		}
	}
}