Pagini recente » Cod sursa (job #2380849) | Cod sursa (job #2095424) | Cod sursa (job #2916618) | Cod sursa (job #1026467) | Cod sursa (job #1710976)
#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);
int pop_Back();
void pushFront(int &x);
int 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;
}
int deq :: pop_Back() {
if(last == NULL) {
return 0;
}
else if(first->val == last->val) {
node *p = last;
int returnedValue = last->val;
first = last = NULL;
delete p;
return returnedValue;
}
else if(first->next == last) {
node *p = last;
int returnedValue = last->val;
first->next = NULL;
last = first;
delete p;
return returnedValue;
}
else {
int returnedValue = last->val;
node *p = last;
last = last->prev;
last->next = NULL;
delete p;
return returnedValue;
}
}
int deq :: pop_Front() {
if(first == NULL)
return 0;
else if(first->val == last->val) {
node *p = first;
int returnedValue = first->val;
first = last = NULL;
delete p;
return returnedValue;
}
else if(first->next == last) {
node *p = first;
int returnedValue = first->val;
first = first->next;
first->prev = NULL;
delete p;
return returnedValue;
}
else {
int returnedValue = first->val;
node *p = first;
first = first->next;
first->prev = NULL;
delete p;
return returnedValue;
}
}
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.assign(N+2, 0);
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(i - K == D.Front() && !D.empty())
D.pop_Front();
if(i >= K)
sol += V[ D.Front() ];
}
cout << sol << '\n';
return 0;
}