Pagini recente » Cod sursa (job #3200799) | Cod sursa (job #34566) | Cod sursa (job #1889110) | Cod sursa (job #2439568) | Cod sursa (job #1329085)
#include <fstream>
using namespace std;
template <typename T>
class Deque {
private:
struct Node {
T item;
Node * prev, * next;
Node() {
prev = next = NULL;
}
};
Node * first, * last;
public:
Deque() {
first = last = NULL;
}
void pushFront(T newItem) {
Node * node = new Node;
node->item = newItem;
if(first == NULL)
first = last = node;
else {
first->prev = node;
node->next = first;
first = node;
}
}
void popFront() {
if(first == NULL)
return;
if(first->next == NULL)
first = last = NULL;
else {
first = first->next;
delete first->prev;
first->prev = NULL;
}
}
void pushBack(T newItem) {
Node * node = new Node;
node->item = newItem;
if(last == NULL)
first = last = node;
else {
last->next = node;
node->prev = last;
last = node;
}
}
void popBack() {
if(last == NULL)
return;
if(last->prev == NULL)
first = last = NULL;
else {
last = last->prev;
delete last->next;
last->next = NULL;
}
}
Node * begin() {
return first;
}
Node * end() {
return last;
}
T front() {
return first->item;
}
T back() {
return last->item;
}
bool empty() {
return (first == NULL);
}
};
Deque < pair<int, int> > deq;
int N, K;
long long Answer;
int main() {
int i, x;
ifstream in("deque.in");
ofstream out("deque.out");
in >> N >> K;
for(i = 1; i <= N; i++) {
for(in >> x; !deq.empty() && deq.back().second > x; deq.popBack());
deq.pushBack(make_pair(i, x));
if(deq.front().first <= i - K)
deq.popFront();
if(i >= K)
Answer += deq.front().second;
}
out << Answer << '\n';
in.close();
out.close();
return 0;
}