Cod sursa(job #3172298)

Utilizator raulandreipopRaul-Andrei Pop raulandreipop Data 20 noiembrie 2023 14:42:25
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <deque>
#include <queue>

using namespace std;
using ll = long long;
const int NMAX = 5e6;
int a[NMAX+1];

int main ()
{
    freopen("deque.in" , "r" , stdin);
    freopen("deque.out" , "w" , stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int n, k; cin >> n >> k;
    deque<int> q;
    for (int i = 1; i <= k; i++)
    {
        cin >> a[i];
        while (q.size() && a[q.front()] >= a[i]) q.pop_front();
        q.push_front(i); 
    }
    ll ans = a[q.back()];
    
    for (int i = k+1; i <= n; i++)
    {
        cin >> a[i];
        while (q.size() && a[q.front()] >= a[i]) q.pop_front();
        q.push_front(i);
        if (q.back() <= i-k)
            q.pop_back();
    //    cout << q.back() << ' ';
        ans += a[q.back()];
    }
    cout << ans << '\n';
}