Cod sursa(job #1363364)

Utilizator anaid96Nasue Diana anaid96 Data 26 februarie 2015 22:06:41
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 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];

//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++;
			insert(value);
			apear[++elem] = value;
		}
		else
			if(type == 2)
			{
				
				fscanf(in, "%d", &value);
				for(int i=1; i<=n; ++i)
					if(heap[i] == apear[value])
					{
						erase(i);
						break;
					}
			}
			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>0 && heap[son] < heap[father])
	{
		swap(heap[son], 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;
	}
}