Cod sursa(job #1363398)

Utilizator anaid96Nasue Diana anaid96 Data 26 februarie 2015 22:29:00
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include<stdio.h>
#include<algorithm>

using namespace std;

FILE *in, *out;

//definitions

//constants
const int sz = (int)2e5+1;

//variables
int operations;
int type, value;
int n, elem;

int apear[sz];
int heap[sz];
int position[sz];

//functions
void insert(int key);
void erase(int pos);

int main(void)
{
	in = fopen("heapuri.in", "rt");
	out = fopen("heapuri.out", "wt");
	
	fscanf(in, "%d", &operations);
	
	while(operations--)
	{
		fscanf(in, "%d", &type);
		
		if(type == 1)
		{
			fscanf(in, "%d", &value);
			n++;
			position[value] = n;
			insert(value);
			apear[++elem] = value;
		}
		else
			if(type == 2)
			{
				
				fscanf(in, "%d", &value);
				erase(position[value]);
			}
			else
				fprintf(out, "%d\n", heap[1]);
	}
	
	fclose(in);
	fclose(out);
	return 0;
}

void insert(int key)
{
	int son = n, father = n/2;
	heap[son] = key;
	
	while( father && heap[son] < heap[father])
	{
		swap(heap[son], heap[father]);
		
		swap(position[heap[son]], position[heap[father]]);
		
		son = father;
		father = son/2;
	}		
	
}

void erase(int pos)
{
	int son = 2*pos, father = pos;
	
	heap[pos] = heap[n];
	n--;
	
	while( son <= n)
	{
		if(son+1 <= n)
			son = heap[son] > heap[son+1] ? son+1 : son;
		
		if(heap[father] > heap[son])
			swap(heap[father], heap[son]);
		else
			break;
	}
}