Pagini recente » Cod sursa (job #634476) | Cod sursa (job #2076759) | Cod sursa (job #1098066) | Cod sursa (job #899033) | Cod sursa (job #806983)
Cod sursa(job #806983)
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
struct lista
{
int info;
int position;
lista *left;
lista *right;
}*start,*end;
int pozmin;
void pop_left()
{
lista *cpy = start;
if (start -> right != NULL)
{
start-> right -> left = NULL;
start = start -> right;
}
else
{
start = NULL;
}
if (start == NULL)
{
end = NULL;
}
delete(cpy);
}
void pop_right()
{
lista *cpy = end;
if (end -> left != NULL)
{
end -> left -> right = NULL;
end = end -> left;
}
else
{
end = NULL;
}
if (end == NULL)
{
start = NULL;
}
delete(cpy);
}
void push_right(int x,int poz)
{
lista *p = new lista();
p -> info = x;
p -> right = NULL;
p -> position = poz;
if (end != NULL)
{
end -> right = p;
p -> left = end;
end = p;
}
else
{
end = new lista();
end = p;
}
if (start == NULL)
{
start = p;
}
pozmin = start -> position;
}
int main()
{
FILE *input = fopen("deque.in","r");
FILE *output = fopen("deque.out","w");
int n,k;
long long sum = 0;
fscanf(input,"%d",&n);
fscanf(input,"%d",&k);
int x;
for (int i=0;i<k;i++)
{
fscanf(input,"%d",&x);
while (end != NULL)
{
if (end -> info >= x) pop_right();
else break;
}
push_right(x,i);
}
pozmin = start -> position;
sum += start -> info;
for (int i=k;i<n;i++)
{
fscanf(input,"%d",&x);
if (pozmin + k - 1< i)
{
pop_left();
pozmin = start -> position;
}
while (end != NULL)
{
if (end -> info >= x) pop_right();
else break;
}
push_right(x,i);
sum += start -> info;
}
fprintf(output,"%lld",sum);
fclose(input);
fclose(output);
return 0;
}