Pagini recente » Cod sursa (job #2854406) | Cod sursa (job #1053129) | Cod sursa (job #648043) | Cod sursa (job #1589232) | Cod sursa (job #1017178)
#include <iostream>
#include <fstream>
using namespace std;
#include <deque>
#include <algorithm>
typedef long long int64;//signed long long
//int e_023_deque()
int main()
{
char* file_name = "deque.in";
//the inputs
int N, K;
int64* v;
//read the inputs
ifstream ifs(file_name);
ifs>>N>>K;
//allocates the vector for storing the numbers
v = new int64[N];
//read the numbers
for (int i = 0; i < N; i++)
{
ifs>>v[i];
//cout<<v[i]<<" "<<endl;
}
ifs.close();
deque<int64> K_deq;
//insert the first K numbers
for (int k = 0; k < K; k++)
{
K_deq.push_back(v[k]);
}
//sort the first k numbers
sort(K_deq.begin(), K_deq.end());
int64 sum_of_mins = K_deq.front();
//for the rest of the values
for (int n = K; n < N; n++)
{
//if the element to be removed is the minimum, remove it now
//otherwise, ignore it; it will be removed later
if (v[n-K] == K_deq.front()) K_deq.pop_front();
//add the new element v[n] into the sequence
//remove all the elements higher than the current element v[n];
while (!K_deq.empty() && K_deq.back() >= v[n]) K_deq.pop_back();
//insert the new element into the queue
K_deq.push_back(v[n]);
//add the minimum to the sum of
sum_of_mins += K_deq.front();
}
ofstream ofs("deque.out");
ofs<<sum_of_mins;
ofs.close();
//release the memory
delete[] v;
return 0;
}