Pagini recente » Cod sursa (job #2958381) | Cod sursa (job #2187284) | Cod sursa (job #2567736) | Cod sursa (job #2335169) | Cod sursa (job #1017324)
#include <iostream>
#include <fstream>
using namespace std;
typedef long long int64;//signed long long
//int e_023_deque()
int main()
{
char* file_name = "deque.in";
//the inputs
int N, K;
//read the inputs
ifstream ifs(file_name);
ifs>>N>>K;
//allocates the vector for storing the numbers
int* v = new int[N];
int* deq_ids = new int[N];
//read the numbers
for (int i = 0; i < N; i++) ifs>>v[i];
ifs.close();
int64 sum_of_mins = 0;
int front_ind = 0, back_ind = -1;
for (int n = 0; n < N; n++)
{
//insert the new element into the proper location
while( front_ind <= back_ind && v[n] <= v[deq_ids[back_ind]]) back_ind--;
deq_ids[++back_ind] = n;
//remove the first element of the current sequence
if (deq_ids[front_ind] == n-K) front_ind++;
//add the minimum to the sum
if (n >= K-1) sum_of_mins += v[deq_ids[front_ind]];
}
ofstream ofs("deque.out");
ofs<<sum_of_mins;
ofs.close();
//release the memory
delete[] v;
delete[] deq_ids;
return 0;
}