Cod sursa(job #2443342)

Utilizator r00t_Roman Remus r00t_ Data 27 iulie 2019 14:32:53
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <fstream>
#include <deque>
#include <algorithm>
#include <vector>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int heap[1000008];

int left_son(int k)
{
	return k * 2;
}

int right_son(int k)
{
	return k * 2 + 1;
}

int parent(int k)
{
	return k / 2;
}

int getMin()
{
	return heap[1];
}

void sift(int N, int k)
{
	int son;
	do
	{
		son = 0;
		if (left_son(k) <= N)
		{
			if (right_son(k) <= N)
			{
				if (heap[left_son(k)] < heap[right_son(k)]) son = left_son(k);
				else son = right_son(k);
			}
			else son = left_son(k);

			if (heap[k] <= heap[son] )
			{
				son = 0;
			}
		}

		if (son)
		{
			swap(heap[son], heap[k]);
			k = son;
		}

	} while (son);


}
void percolate(int n, int k)
{
	if(k!=1)
	if (heap[parent(k)] > heap[k])
	{
		swap(heap[parent(k)], heap[k]);
		percolate(n, parent(k));
	}
}

void buildHeap(int n, int *vect)
{
	for (int i = 1; i <= n; i++)
		heap[i] = vect[i];
	for (int i = n / 2; i >= 1; i--)
	{
		sift(n, i);
	}
}

void heapInsert(int &n, int x)
{
	heap[++n] = x;
	percolate(n, n);
}

void heapErase(int &n, int k)
{
	heap[k] = heap[n];
	n--;

	if (heap[k] < heap[parent(k)])percolate(n, k);
	else
	{
		sift(n, k);
	}
}

void heapSearch(int &n, int k, int x, int &found)
{
	if (found != 0) return;
	if (heap[k] == x)found = k;
	else
	{
		if (left_son(k) <= n && heap[left_son(k)] <= x)
			heapSearch(n, left_son(k), x, found);
		if (right_son(k) <= n && heap[right_son(k)] <= x)
			heapSearch(n, right_son(k), x, found);
	}
	

}


int main()
{
	ios::sync_with_stdio(false);
	int n, cmd, x, hSize = 0;
	vector<int>hist;
	fin >> n;
	for (int i = 1; i <= n; i++)
	{
		fin >> cmd;
		if (cmd == 1)
		{
			fin >> x;
			hist.push_back(x);
			heapInsert(hSize, x);
		}
		if (cmd == 2)
		{
			fin >> x;
			int found = 0;
			heapSearch(hSize, 1, hist[x - 1], found);
			if(found != 0)
				heapErase(hSize, found);
		}
		if (cmd == 3)
		{
			fout << heap[1] << '\n';
		}
	}



	return 0;
}