Pagini recente » Cod sursa (job #2460943) | Cod sursa (job #1640980) | Cod sursa (job #2679748) | Cod sursa (job #2266531) | Cod sursa (job #1710980)
#include <iostream>
#include <fstream>
#include <vector>
struct node {
int val;
node *prev, *next;
};
class deq {
node *first, *last;
public:
deq();
~deq();
bool empty() { return (first == NULL && last == NULL); }
int Back();
int Front();
void pushBack(int &x);
void pop_Back();
void pushFront(int &x);
void pop_Front();
};
deq :: deq() {
first = NULL;
last = NULL;
}
deq :: ~deq() {
node *q, *p = first;
while(p->next != NULL) {
q = p;
p = p->next;
delete q;
}
first = last = NULL;
}
int deq :: Back() {
return last->val;
}
int deq :: Front() {
return first->val;
}
void deq :: pushBack(int &x) {
node *newNode = new node;
newNode->val = x;
newNode->next = NULL;
newNode->prev = last;
last = newNode;
if(first == NULL)
first = last;
else
last->prev->next = last;
}
void deq :: pushFront(int &x) {
node *newNode = new node;
newNode->val = x;
newNode->next = first;
newNode->prev = NULL;
first = newNode;
if(last == NULL)
last = first;
else
first->next->prev = first;
}
void deq :: pop_Back() {
if(last == NULL)
return;
else if(first->val == last->val) {
node *p = last;
first = last = NULL;
delete p;
}
else if(first->next == last) {
node *p = last;
first->next = NULL;
last = first;
delete p;
}
else {
node *p = last;
last = last->prev;
last->next = NULL;
delete p;
}
}
void deq :: pop_Front() {
if(first == NULL)
return;
else if(first->val == last->val) {
node *p = first;
first = last = NULL;
delete p;
}
else if(first->next == last) {
node *p = first;
first = first->next;
first->prev = NULL;
delete p;
}
else {
node *p = first;
first = first->next;
first->prev = NULL;
delete p;
}
}
using namespace std;
int main()
{
freopen("deque.in", "rt", stdin);
freopen("deque.out", "wt", stdout);
int N, K;
long long sol = 0;
scanf("%d%d", &N, &K);
vector<int> V;
V.resize(N+2);
deq D;
for(int i = 1; i <= N; ++i) {
scanf("%d", &V[i]);
while(!D.empty() && V[i] <= V[ D.Back() ])
D.pop_Back();
D.pushBack(i);
if(!D.empty() && i - K == D.Front())
D.pop_Front();
if(i >= K)
sol += (long long)V[ D.Front() ];
}
cout << sol << '\n';
return 0;
}