Cod sursa(job #2775826)

Utilizator radu.z5Zamfirescu Radu Ioan radu.z5 Data 17 septembrie 2021 15:09:54
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#include <utility>
#include <list>

using namespace std;

#define val(p) p.first
#define pos(p) p.second

long deque(ifstream &in) {
    int n, k;
    in >> n >> k;

    long sum = 0L;
    list<pair<int, int>> deq;
    int i, x;

    int firstIdWithinLastSubstr = n - k;
    for (i = 0; i < k; i++) {
        in >> x;
        while (!deq.empty() && val(deq.back()) >= x)
            deq.pop_back();
        if (!deq.empty() && i > firstIdWithinLastSubstr)
            continue;
        deq.push_back({x, i});
    }

    sum += val(deq.front());
    if (pos(deq.front()) == 0)
        deq.pop_front();

    while (i < n) {
        in >> x;
        while (!deq.empty() && val(deq.back()) >= x)
            deq.pop_back();
        deq.push_back({x, i});
        sum += val(deq.front());
        if (pos(deq.front()) == i - k + 1)
            deq.pop_front();
        i++;
    }
    return sum;
}

int main(void) {
    ifstream in("deque.in");
    ofstream out("deque.out");
    out << deque(in);
    in.close();
    out.close();
    return 0;
}