Cod sursa(job #1615894)

Utilizator ehsanpEhsan Poursaeed ehsanp Data 26 februarie 2016 22:27:57
Problema Deque Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <iostream>
#include <deque>

using namespace std;

const int mxn = 5000010;

int a[mxn];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n, k;
	cin >> n >> k;
	for (int i = 0; i < n; ++i) {
		cin >> a[i];
	}
	deque < pair<int,int> > cand;
	for (int i = 0; i < k - 1; ++i) {
		while (!cand.empty() && cand.back().first > a[i]) {
			cand.pop_back();
		}
		cand.push_back( make_pair(a[i], i) );
	}
	long long ans = 0;
	for (int i = k - 1; i < n; ++i) {
		while (!cand.empty() && cand.front().second <= i - k) {
			cand.pop_front();
		}
		while (!cand.empty() && cand.back().first > a[i]) {
			cand.pop_back();
		}
		cand.push_back( make_pair(a[i], i) );
		ans += cand.front().first;
	}
	cout << ans << "\n";
}