Pagini recente » Cod sursa (job #1551315) | Cod sursa (job #906040) | Cod sursa (job #359563) | Cod sursa (job #1368090) | Cod sursa (job #455218)
Cod sursa(job #455218)
#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;
}