Cod sursa(job #2450959)

Utilizator urweakurweak urweak Data 25 august 2019 11:16:33
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#define NMax 5000010

using namespace std;
ifstream in("deque.in");
ofstream out("deque.out");

int N, K;
int A[NMax], Deque[NMax];
long long Sum;

int main(){
	in >> N >> K;

	for(int i = 1; i<=N; i++)
		in >> A[i];

	int Front = 1, Back = 0; // This represent a simple queue(*not deque);

	for(int i = 1; i<=N; i++){
		while(Front <= Back && A[i] <= A[ Deque[Back] ]) Back--; // If the current value is lower than the value of the last element in deque delete the last element
		
		//Add the position of the current element in deque
		Deque[++Back] = i ;

		//If the lowest number coincide wiht the one on the position i-K, eliminate the position from deque, because this dosen't matter for the steps >=i
		if(Deque[Front] == i-K) Front++; 

		//Print the minimum, this is in the top of the deque
		if(i>=K) Sum+=A[ Deque[Front] ];
	}
	out << Sum;
	return 0;
}