Cod sursa(job #3125646)

Utilizator Alexco2003Codarcea Alexandru-Christian Alexco2003 Data 3 mai 2023 22:47:52
Problema Deque Scor 25
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream f1("deque.in");
    ofstream f2("deque.out");

    int N, K;
    f1 >> N >> K;

    int A[N], S = 0, d[N], front = 0, back = 0;

    for (int i = 0; i < N; i++)
    {
        f1 >> A[i];

        // Remove elements from the back of the deque that are greater than or equal to A[i]
        while (back > front && A[d[back-1]] >= A[i])
        {
            back--;
        }

        // Add current index to the back of the deque
        d[back++] = i;

        // If the deque has K elements, remove the front element and add its value to S
        if (i >= K-1)
        {
            // Remove elements from the front of the deque that are no longer in the current window
            while (front < back && d[front] <= i-K)
            {
                front++;
            }

            // If there are any elements left in the deque, add the value of the smallest element to S
            if (front < back)
            {
                S += A[d[front]];
            }
        }
    }

    f2 << S;

    f1.close();
    f2.close();
    return 0;
}