Pagini recente » Cod sursa (job #305611) | Cod sursa (job #1860522) | Cod sursa (job #3141103) | Cod sursa (job #303153) | Cod sursa (job #843276)
Cod sursa(job #843276)
#include <stdio.h>
#include <stdlib.h>
#define MAXN 5000001
int v[MAXN];
int N,K;
////////////// QUEUE ///////////////////
typedef struct tagNode{
int position;
struct tagNode* next;
struct tagNode* back;
}Node;
typedef struct tagQueue{
Node *start;
Node *end;
}Queue;
void initQueue(Queue *q)
{
q->start = NULL;
q->end = NULL;
}
void pushQueue(Queue *q, int pos)
{
Node *aux = q->end;
while( aux != NULL && v[pos] <= v[aux->position] )
aux = aux->back;
Node *new = malloc(sizeof(Node));
new->position = pos;
new->next = NULL;
new->back = aux;
q->end = new;
if( aux == NULL ){
q->start = new;
}
else{
aux->next = new;
}
}
int topQueue(Queue *q)
{
return q->start->position;
}
void popQueue(Queue *q, int v)
{
if( q->start->position != v )
return;
if( q->start->next == NULL){
free(q->start);
q->start = NULL;
q->end = NULL;
}
else{
q->start = q->start->next;
free(q->start->back);
q->start->back = NULL;
}
}
int isEmptyQueue(Queue *q)
{
return q->start == NULL;
}
////////////////////////////////////////
int main(int argc, char* argv[])
{
freopen("deque.in","r",stdin);
freopen("deque.out","w",stdout);
scanf("%d %d",&N,&K);
int i;
for(i=1;i<=N;i++)
scanf("%d",&v[i]);
Queue q;
long long sum = 0;
initQueue(&q);
for(i=1;i<=K;i++)
pushQueue(&q,i);
sum += v[topQueue(&q)];
for(i=K+1;i<=N;i++){
popQueue(&q, i-K);
pushQueue(&q, i);
sum += v[topQueue(&q)];
}
printf("%lld",sum);
return 0;
}