Cod sursa(job #3323748)

Utilizator Stefanstef99Stefan Puica Stefanstef99 Data 19 noiembrie 2025 17:16:45
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("deque.in");
ofstream fout("deque.out");

/**
9 4
-7 9 2 4 8 5 6 7 1

d =  2 4 8

*/

int n, k, a[5000001];
deque <int> d;

int main()
{
    int i, x;
    long long s;
    fin >> n >> k;
    for(i = 1; i <= n; i++) fin >> a[i];
    for(i = 1; i <= k; i++)
    {
        x = a[i];
        while(!d.empty() && a[d.back()] >= x)
            d.pop_back();
        d.push_back(i);
    }
    s = a[d.front()];
    for(i = k + 1; i <= n; i++)
    {
        x = a[i];
        while(!d.empty() && a[d.back()] >= x)
            d.pop_back();
        d.push_back(i);
        if(d.front() == i - k) d.pop_front();
        s += a[d.front()];
    }
    fout << s << '\n';
    return 0;
}