Cod sursa(job #455218)

Utilizator tomescu_alinTomescu Alin tomescu_alin Data 13 mai 2010 10:53:46
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
#include <deque>
#include <vector>
using namespace std;

long long getSumOfMins(std::vector<long>& v, int k)
{
	std::deque<int> deq;
	
	long long sum = 0;
	
	for(int i = 0; i < v.size(); i++)
	{
		//	Pop off elements that are too large to be the minimum in
		//	the current k-length-subsequence.
		while(!deq.empty())
		{
			if(v[i] < v[deq.back()])
				deq.pop_back();
			else
				break;
		}
		
		//	Add the current element at the end of the queue.
		deq.push_back(i);
		
		//	Pop off the min element from the previous [i, i+k] range 
		//	that is not contained within the new [i + e, i + e + k] range.
		if(deq.front() <= i - k)
			deq.pop_front();
		
		//	Check if we're far enough into the array, namely if we're past k elements,
		//	to determine the min. for the current subsequence.
		if((i + 1) - k >= 0)
			sum += v[deq.front()];
	}
	
	return sum;
}

int main(int argc, char * argv[]) 
{
	
	const char * inFile = "deque.in";
	const char * outFile = "deque.out";
	
	ifstream fin(inFile);
	ofstream fout(outFile);
	
	/**
	 *	Read the data in.
	 */
	int length, k;
	fin >> length >> k;
	
	std::vector<long> v;
	v.reserve(length);
	
	for(int i = 0; i < length; i++)
	{
		long number;
		fin >> number;
		v.push_back(number);
	}
	
	fout << getSumOfMins(v, k) << endl;
	
	fin.close();	
	fout.close();

	return 0;
}