Cod sursa(job #1051461)

Utilizator BionicMushroomFMI - Dumitrescu Tiberiu Alexandru BionicMushroom Data 10 decembrie 2013 03:38:58
Problema Deque Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include<fstream>
using namespace std;

int *heap, len = -1, *v;

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

void sift(int nod)
{
	int son;
	do
	{
		son = 0;
		if (nod * 2 <= len)
		{
			son = nod * 2;
			if (nod * 2 + 1 <= len && v[heap[nod * 2 + 1]] < v[heap[nod * 2]])
				son = nod * 2 + 1;
			if (v[heap[son]] >= v[heap[nod]])
				son = 0;
		}

		if (son)
		{
			interschimba(heap[nod], heap[son]);
			nod = son;
		}
	} while (son);
}

void percolate(int nod) 
{
	int key = heap[nod];
	while ((nod > 1) && (v[key] > v[heap[nod / 2]])) 
	{
		heap[nod] = heap[nod / 2];
		nod /= 2;
	}
	heap[nod] = key;
}

void insert(int nod) 
{
	heap[++len] = nod;
	percolate(len);
}

void cut(int nod) {
	heap[nod] = heap[len];
	--len;
	if ((nod > 1) && (v[heap[nod]] > v[heap[nod / 2]])) 
		percolate(nod);
	else
		sift(nod);
}

int main()
{
	int n, k;
	long long sum = 0;
	ifstream f("deque.in");
	f >> n >> k;
	v = new int[n];
	heap = new int[n];
	for (int i = 0; i < n; i++)
	{
		f >> v[i];
		while (len >= 0 && v[heap[0]] > v[i])
			cut(0);
		insert(i);
		if (i >= k - 1)
		{
			sum += v[heap[0]];
			if (heap[0] == i + 1 - k)
				cut(0);
		}
	}
	f.close();
	ofstream g("deque.out");
	g << sum;
	g.close();
	return 0;
}