Cod sursa(job #1051468)

Utilizator BionicMushroomFMI - Dumitrescu Tiberiu Alexandru BionicMushroom Data 10 decembrie 2013 04:31:07
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include<stdio.h>
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;
	freopen("deque.in", "r", stdin);
	scanf("%d %d", &n, &k);
	v = new int[n];
	heap = new int[n];
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &v[i]);
		while (len >= 0 && (i - heap[0] >= k))
			cut(0);
		while (len >= 0 && v[heap[0]] >= v[i])
			cut(0);
		insert(i);
		if (i >= k - 1)
			sum += v[heap[0]];
	}
	freopen("deque.out", "w", stdout);
	printf("%lld", sum);
	return 0;
}