Cod sursa(job #2891529)

Utilizator matthriscuMatt . matthriscu Data 18 aprilie 2022 21:56:16
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.55 kb
#include <bits/stdc++.h>
using namespace std;

#define problem "deque"
#define NMAX 5000005

int v[NMAX];

int main()
{
	freopen(problem ".in", "r", stdin);
	freopen(problem ".out", "w", stdout);
	
	int n, k;
	scanf("%d%d", &n, &k);

	for (int i = 1; i <= n; ++i)
		scanf("%d", &v[i]);

	long long ans = 0;
	deque<int> dq;

	for (int i = 1; i <= n; ++i) {
		while (!dq.empty() && v[dq.back()] >= v[i])
			dq.pop_back();
		while (!dq.empty() && dq.front() <= i - k)
			dq.pop_front();
		dq.push_back(i);
		ans += (i >= k) * v[dq.front()];
	}

	printf("%lld\n", ans);
}