Cod sursa(job #1017320)

Utilizator dm1sevenDan Marius dm1seven Data 27 octombrie 2013 17:32:26
Problema Deque Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#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] == v[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;
}