Pagini recente » Cod sursa (job #1668737) | Cod sursa (job #3146541) | Cod sursa (job #24164) | Cod sursa (job #2550473) | Cod sursa (job #2775826)
#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;
}