Cod sursa(job #1060469)

Utilizator miu_mik93FMI - Paduraru Miruna miu_mik93 Data 18 decembrie 2013 00:05:11
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <iostream>
#include <string>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <queue>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <stdarg.h>
#include <stdio.h>
using namespace std;
//#include <unordered_map>
#define NMAX 200000

int N, heap[NMAX], k, indice = 1, pos[NMAX], a[NMAX];

void swap(int &a, int &b)
{
    int aux;
    aux = a;
    a = b;
    b = aux;
}

void printMin (FILE *g)
{
	fprintf (g, "%d\n", a[heap[1]]);
}

void goUp (int *heap, int k)
{
	while (k > 1 && a[heap[k]] < a[heap[k/2]])
	{
		swap (heap[k], heap[k/2]);
		
		pos[heap[k]] = k;
		pos[heap[k / 2]] = k / 2;
		k /= 2;
	}
}

void insert(int *heap, int &k, int x)
{
	k++;
	heap[k] = indice;
	pos[indice] = k;
	goUp (heap, k);
	indice++;
}

void goDown (int *heap, int &k, int poz)
{
	if (poz * 2 > k)
		return;
	int poz_c = poz * 2;
	if ( poz_c + 1 <= k && a[heap[poz_c + 1]] < a[heap[poz_c]] ) 
		poz_c++;
	if ( a[heap[poz_c]] < a[heap[poz]] );
	{
		swap (a[heap[poz_c]], a[heap[poz]]);
		
		pos[heap[poz]] = poz;
		pos[heap[poz_c]] = poz_c;
		goDown (heap, k, poz_c);
	}
}

void deletePoz (int *heap, int &k, int poz)
{
	pos[heap[poz]] = 0;
	heap[poz] = heap[k];
	pos[heap[k]] = poz;
	k--;
	if ( a[heap[poz]] < a[heap[poz/2]] )
		goUp (heap, poz);
	else
		goDown (heap, k, poz);
}

int main()
{
	FILE *f = fopen ("heapuri.in", "r");
	FILE *g = fopen ("heapuri.out", "w");
	
	int cod;
	fscanf (f, "%d", &N);
	for (int i = 0; i < N; i++)
	{
		fscanf (f, "%d", &cod);
		int x;
		if ( cod == 1 || cod == 2 )
		{
			fscanf (f, "%d", &x);
			if ( cod  == 1 )
			{
				a[indice] = x;
				insert(heap, k, indice);
			}
			else
			{
				deletePoz (heap, k, pos[x]);
			}
		}
		else
			printMin(g);
	}
	

	fclose(f); fclose(g);
	return 0;
}