Cod sursa(job #3358972)

Utilizator Cezar2009Cezar Mihai Titihazan Cezar2009 Data 22 iunie 2026 16:51:46
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>

using namespace std;

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

int main() {
    // Fast I/O
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int N, K;
    if (!(fin >> N >> K)) return 0;

    vector<long long> A(N);
    for (int i = 0; i < N; ++i) {
        fin >> A[i];
    }

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

    for (int i = 0; i < N; ++i) {
        // Maintain monotonic increasing order of values
        // Remove elements from back that are >= current element
        while (!dq.empty() && A[dq.back()] >= A[i]) {
            dq.pop_back();
        }

        // Add current index
        dq.push_back(i);

        // Remove indices that are out of the current window [i-K+1, i]
        if (dq.front() <= i - K) {
            dq.pop_front();
        }

        // If we have processed at least K elements, the front is the minimum
        if (dq.size() >= 1) { // Note: Since we push i, size is at least 1. 
            // The window is valid only if i >= K-1.
            // However, strictly speaking, the first valid window ends at index K-1.
            // So we check if i >= K - 1.
        }

        // Correct condition for the first full window:
        if (i >= K - 1) {
            // The front of the deque is the index of the minimum in the current window
            total_sum += A[dq.front()];
        }
    }

    // Output result to deque.out
    // Since standard streams are used here, we simulate file output or redirect.
    // For strict file output as per problem description:
    // FILE* out = fopen("deque.out", "w");
    // fprintf(out, "%lld\n", total_sum);
    // fclose(out);

    fout << total_sum << endl;

    return 0;
}