Cod sursa(job #1933538)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 20 martie 2017 19:48:39
Problema Deque Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <cstdio>
#include <iostream>
#include <deque>

using namespace std;

int n, m;
deque<int> q;
int numere[5000005];

void citire()
{
	scanf("%lld %lld", &n, &m);
	
	for(int i = 0; i < n; i++)
	{
		scanf("%lld", &numere[i]);
	}
}

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

	citire();

	int x;

	for(int k = 0; k < m - 1; k++)
	{
		x = numere[k];

		while(q.empty() == false)
		{
			if(numere[q.back()] > x)
			{
				q.pop_back();
			}
			else
			{
				q.push_back(k);
				break;
			}
		}

		if(q.empty() == true)
		{
			q.push_back(k);
		}
	}

	long long suma = 0;
	
	for(int k = m - 1; k < n; k++)
	{
		x = numere[k];
		
		if(k - q.front() >= m)
		{
			q.pop_front();
		}

		while(q.empty() == false)
		{
			if(numere[q.back()] > x)
			{
				q.pop_back();
			}
			else
			{
				q.push_back(k);
				break;
			}
		}

		if(q.empty() == true)
		{
			q.push_back(k);
		}
		
		suma += numere[q.front()] * 1LL;
	}

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

	return 0;
}