Cod sursa(job #3125824)

Utilizator GFA03Gavrila Florin-Alexandru GFA03 Data 4 mai 2023 16:46:25
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <bits/stdc++.h>

#define maxElem 5000005

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

int deque[maxElem];
int poz[maxElem];

int main(){
    int n, k;
    int front = 1, back = 0;
    fin >> n >> k;
    int x, cnt = 0;
    long long int S = 0;
    for(int i = 1; i <= n; ++i) {
        fin >> x;
        if(front <= back && cnt - k >= poz[front]) {
            front++;
        }
        if(front <= back)
            while(front <= back && x <= deque[back]){
                back--;
            }
        deque[++back] = x;
        poz[back] = cnt;
        if(cnt >= k-1)
            S += deque[front];
        cnt++;
    }
    fout << S;

    // for(int i = 0; i < n; ++i)
    //     std::cout << v[i] << " ";
    // std::cout << '\n';
    long long sum = 0;
}