Cod sursa(job #229414)

Utilizator pauldbPaul-Dan Baltescu pauldb Data 10 decembrie 2008 02:15:10
Problema Deque Scor Ascuns
Compilator cpp Status done
Runda Marime 1.26 kb
#include <stdio.h>
#include <stdlib.h>

using namespace std;

#define maxn 5000010
#define maxl 12

long long sum;
int n, k, l;
int a[maxn];
int h[maxn], p[maxn];
char buff[maxl];

void push(int x)
{
	int aux;

	while (x/2>=1 && a[h[x]] < a[h[x/2]])
	{
		aux = h[x], h[x] = h[x/2], h[x/2] = aux;

		p[h[x]] = x;
		p[h[x/2]] = x/2;
		x /= 2;
	}
}

void pop(int x)
{
	int aux, y = 0;

	while (x != y)
	{
		y = x;
		if (y*2<=l && a[h[x]]>a[h[y*2]]) x = y*2;
		if (y*2+1<=l && a[h[x]]>a[h[y*2+1]]) x = y*2+1;

		aux = h[x], h[x] = h[y], h[y] = aux;
		p[h[x]] = x;
		p[h[y]] = y;
	}
}

int main()
{
	freopen("deque.in", "r", stdin);
	freopen("deque.out", "w", stdout);

	scanf("%d %d ", &n, &k);

	int i, j, x;

	for (i=1; i<=n; i++)
	{
		fgets(buff, maxl, stdin);

//		for (j = buff[0] == '-'; buff[j]>='0' && buff[j]<='9'; j++) a[i] = a[i] * 10 + buff[j] - '0';
//		if (buff[0] == '-') a[i] = -a[i];
		
		scanf("%d ", &a[i]);
	
		l++;
		h[l] = i;
		p[h[l]] = l;
		push(l);

		while (h[1] <= i-k)
		{
			h[1] = h[l--];
			p[h[1]] = 1;
			pop(1);
		}

		if (i >= k) 
		{
			sum += a[h[1]];
		/*	x = a[h[1]], j = 0;
			if (x < 0) printf("-");
			for (; x; x/=10) buff[++j] = abs(x%10) + '0';
			for (; j; j--) printf("%c", buff[j]);
			printf("\n");*/
		}
	}

	printf("%lld\n", sum);

	return 0;
}