Cod sursa(job #244686)

Utilizator alex23alexandru andronache alex23 Data 15 ianuarie 2009 20:08:10
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <iostream>
#define NMAX 200005

using namespace std;

FILE *f = fopen("heapuri.in", "r"), *g = fopen("heapuri.out", "w");

int nrElemente = -1, a[NMAX], v[NMAX], final;

int addHeap(int x)
{
	a[++nrElemente] = x;
	int i = nrElemente;
	while (a[i] < a[(i - 1) / 2])
	{
		int aux = a[i];
		a[i] = a[(i - 1) / 2];
		a[(i - 1) / 2] = aux;
		i = (i - 1) / 2;
	}

	return 0;
}

int poz(int i, int k)
{
	/*
	int x;
	if (a[i] == k) return i;
	if (a[i] < k) 
	{
		if (2 * i + 2 <= nrElemente) return poz(2 * i + 1, k) + poz(2 * i + 2, k);
		else
		{
			if (2 * i + 1 <= nrElemente) return poz(2 * i + 1, k);
			else return 0;
		}
	}
	if (a[i] > k) return 0;
	*/
	if (a[i] == k) final = i;
	else
		if (a[i] < k)
		{
			if ((2 * i + 1 <= nrElemente) && (a[2 * i + 1] <= k)) poz(2 * i + 1, k);
			if ((2 * i + 2 <= nrElemente) && (a[2 * i + 2] <= k)) poz(2 * i + 2, k);
		}
	return 0;
}

int removeHeap(int k)
{
	poz(0, k);
	//trebuie sa caut pozitia pe care se afla k in heap
	int i = final;
	/*
	for (int j = 0; j <= nrElemente; ++j)
		printf("%d ", a[j]);
	printf("\n%d %d \n" ,k, final);
	*/
	a[i] = a[nrElemente--];
	int s = 2 * i + 1, d = 2 * i + 2;
	while ((d <= nrElemente) && ((a[s] < a[i]) || (a[d] < a[i])))
	{
		if ((a[i] > a[s]) && (a[i] > a[d]))
		{
			if (a[s] > a[d])
			{
				int aux = a[i];
				a[i] = a[d];
				a[d] = aux;
				i = d;
			}
			else
			{
				int aux = a[i];
				a[i] = a[s];
				a[s] = aux;
				i = s;
			}
		}
		else
		{
			if (a[i] > a[s])
			{
				int aux = a[i];
				a[i] = a[s];
				a[s] = aux;
				i = s;
			}
			else
			{
				int aux = a[i];
				a[i] = a[d];
				a[d] = aux;
				i = d;
			}
		}
		s = 2 * i + 1;
		d = 2 * i + 2;
	}
	if ((2 * i + 1 <= nrElemente) && (a[i] > a[2 * i + 1]))  
	{
		int aux = a[2 * i + 1];
		a[2 * i + 1] = a[i];
		a[i] = aux;
		i = 2 * i + 1;
	}

	return 0;
}

int main()
{
	int N;
	fscanf(f, "%d", &N);
	int q = 0;
	for (int i = 0; i < N; ++i)
	{
		int n, x;
		fscanf(f, "%d", &n);
		if (n != 3)
		{
			fscanf(f, "%d", &x);
		}
		if (n == 1) 
		{
			addHeap(x);
			v[q++] = x;
		}
		if (n == 3)
		{
			fprintf(g, "%d\n", a[0]);
		}
		if (n == 2)
		{
			//printf("remove%d\n", v[x]);
			removeHeap(v[x - 1]);
		}
	}

	fclose(f);
	fclose(g);

	return 0;
}