Pagini recente » Cod sursa (job #33034) | Cod sursa (job #2036578) | Cod sursa (job #1216777) | Cod sursa (job #243231) | Cod sursa (job #984176)
Cod sursa(job #984176)
#include <fstream>
class Deque
{
struct Node
{
int data;
Node *next;
};
Node *first, *last;
public:
Deque() : first(NULL), last(NULL) { }
~Deque()
{
while(!empty())
pop_front();
}
void push_front(int x)
{
if(first == NULL)
{
first = new Node();
first->data = x;
last = first;
}
else
{
Node *c = first;
first = new Node();
first->data = x;
first->next = c;
}
}
void push_back(int x)
{
if(last == NULL)
push_front(x);
else
{
last->next = new Node();
last = last->next;
last->data = x;
}
}
void pop_front()
{
if(last == first)
{
Node *c = first;
first = last = NULL;
delete c;
}
else
{
Node *c = first;
first = first->next;
delete c;
}
}
void pop_back()
{
if(last == first)
pop_front();
else
{
Node *c = first;
while(c->next != last)
c = c->next;
c->next = NULL;
delete last;
last = c;
}
}
int front()
{
if(empty()) return 0;
return first->data;
}
int back()
{
if(empty()) return 0;
return last->data;
}
bool empty()
{
return first == NULL;
}
};
int main()
{
std::ifstream in("deque.in");
std::ofstream out("deque.out");
Deque myDeq;
int nV;
int k;
in >> nV >> k;
int *nArr = new int[nV + 1];
for(int i = 1; i <= nV; i++)
in >> nArr[i];
long long sum = 0;
for(int i = 1; i <= nV; i++)
{
while(myDeq.front() <= i - k && !myDeq.empty())
myDeq.pop_front();
while(nArr[myDeq.back()] >= nArr[i] && !myDeq.empty())
myDeq.pop_back();
myDeq.push_back(i);
if(i >= k)
sum += nArr[myDeq.front()];
}
out << sum;
return 0;
}