Cod sursa(job #1053017)

Utilizator rucarRucareanu Alexandru rucar Data 12 decembrie 2013 01:07:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <stdlib.h>
#include <stdio.h>

struct elem{
	int val, poz;
};

int poz_cron[200000];
            /////
void swap(elem *a, elem *b)
{
	elem aux = *a;
	*a = *b;
	*b = aux;
}

void up(int poz, elem *heap)
{
	while (poz > 1 && heap[poz].val < heap[poz / 2].val)
	{
		swap(&heap[poz], &heap[poz / 2]);
		poz_cron[heap[poz].poz] = poz;
		poz_cron[heap[poz / 2].poz] = poz / 2;
		poz /= 2;
	}
}

void down(int poz, elem *heap,int n)
{
	while (poz * 2 + 1 <= n && (heap[poz].val>heap[poz * 2].val || heap[poz].val > heap[poz * 2 + 1].val))
	{
		int poz1 = poz * 2;
		if (heap[poz * 2 + 1].val < heap[2 * poz].val)
			poz1 = poz * 2 + 1;
		swap(&heap[poz], &heap[poz1]);
		poz_cron[heap[poz].poz] = poz;
		poz_cron[heap[poz1].poz] = poz1;
		poz = poz1;
	}
	if (poz * 2 <= n && heap[poz].val >heap[poz * 2].val)
	{
		swap(&heap[poz], &heap[poz * 2]);
		poz_cron[heap[poz].poz] = poz;
		poz_cron[heap[poz*2].poz] = poz*2;
	}
}

void insert(elem*heap, int x, int &n,int &counter)
{
	heap[++n].val = x;
	heap[n].poz = ++counter;
	poz_cron[counter] = n;
	int poz = n;
	up(poz, heap);
}

void create(int *v, elem *heap, int n)
{
	int i, n1 = 0;
	for (i = 0; i < n; i++)
		insert(heap, v[i], n1,n);
}

int min(elem *heap)
{
	return heap[1].val;
}

int search(int *heap,int n,int x)
{
	int i;
	for (i = 1; i <= n;i++)
	    if (heap[i] == x) 
			return i;
	return -1;
}

void del(int poz, elem *heap,int &n)
{
	if (poz > 0)
	{
		swap(&heap[poz], &heap[n]);
		poz_cron[heap[poz].poz] = poz;
		n--;
		up(poz, heap);
		down(poz, heap, n);
	}
}

              /////

void heapuri()
{
	FILE*f = fopen("heapuri.in", "r"), *g = fopen("heapuri.out", "w");
	int n, i, cod, x, n1 = 0,counter=0;
	fscanf(f, "%d", &n);
	elem*heap = (elem *)malloc(sizeof(elem)*n);
	int *pozi = (int *)malloc(sizeof(int)*n);
	for (i = 1; i <= n; i++)
	{
		fscanf(f, "%d", &cod);
		switch (cod)
		{
		case 1:
			fscanf(f, "%d", &x);
			insert(heap, x, n1,counter);
			break;
		case 2:
			fscanf(f, "%d", &x);
			del(poz_cron[x], heap, n1);
			break;
		case 3:
			fprintf(g, "%d\n", min(heap));
			break;
		}

	}

}
   
int main()
{
	heapuri();
	return 0;
}