Pagini recente » Cod sursa (job #3246249) | Cod sursa (job #3273989) | Cod sursa (job #147526) | Cod sursa (job #334747) | Cod sursa (job #1329079)
#include <fstream>
#define Nmax 5000100
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 <int> deq;
int N, K, A[Nmax];
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 >> A[i]; !deq.empty() && A[deq.back()] > A[i]; deq.popBack());
deq.pushBack(i);
if(deq.front() <= i - K)
deq.popFront();
if(i >= K)
Answer += A[deq.front()];
}
out << Answer << '\n';
in.close();
out.close();
return 0;
}