Pagini recente » Cod sursa (job #562784) | Cod sursa (job #756841) | Cod sursa (job #1832376) | Cod sursa (job #2161043) | Cod sursa (job #972695)
Cod sursa(job #972695)
#include<stdio.h>
#include<stdlib.h>
struct Elem{
int value;
int before;
struct Elem *prev, *next;
};
class Deque{
public:
struct Elem *pHead, *pTail;
Deque(){
pHead = new struct Elem;
pTail = new struct Elem;
pHead = NULL;
pTail = NULL;
}
~Deque(){}
void addBack(int info, int ant) {
struct Elem *paux;
paux = new struct Elem;
paux->value = info;
paux->before = ant;
paux->prev = pTail;
paux->next = NULL;
if (pTail != NULL)
pTail->next = paux;
pTail = paux;
if (pHead == NULL)
pHead = pTail;
}
void addFront(int info, int ant) {
struct Elem *paux;
paux = new struct Elem;
paux->value = info;
paux->before = ant;
paux->prev = NULL;
paux->next = pHead;
if (pHead != NULL)
pHead->prev = paux;
pHead = paux;
if (pTail==NULL)
pTail = pHead;
}
void removeFront() {
struct Elem *paux;
if (pHead != NULL) {
paux = pHead->next;
if (pHead == pTail)
pTail = NULL;
delete pHead;
pHead = paux;
if (pHead != NULL)
pHead->prev = NULL;
}
else
fprintf(stderr, "Error - The deque is empty!\n");
}
void removeBack() {
struct Elem *paux;
if (pTail != NULL) {
paux = pTail->prev;
if (pHead == pTail)
pHead = NULL;
delete pTail;
pTail = paux;
if (pTail != NULL)
pTail->next = NULL;
}
else
fprintf(stderr, "Error - The deque is empty!\n");
}
int isEmpty() {
if(pHead == NULL)
return 1;
return 0;
}
};
int main(){
int i, K, N, x, r, n;
long long S = 0;
FILE *pf, *pg;
pf = fopen("deque.in", "r");
pg = fopen("deque.out", "w");
fscanf(pf, "%d %d", &N, &K);
class Deque D;
n = 0;
for(i=1; i<=N; i++){
fscanf(pf, "%d", &x);
if(D.isEmpty()){
D.addFront(x, 0);
n++;
}
else
if(D.pTail != NULL && D.pTail->value >= x){
r = 0;
while(D.pTail != NULL && D.pTail->value >= x){
r = r + D.pTail->before + 1;
D.removeBack();
}
D.addBack(x, r);
n++;
}
else{
D.addBack(x, 0);
n++;
}
if(n == K){
if(D.pHead != NULL && D.pHead->before == 0){
S = S + D.pHead->value;
D.removeFront();
}
else{
D.pHead->before--;
S = S + D.pHead->value;
}
n--;
}
}
fprintf(pg, "%lld\n", S);
fclose(pf);
fclose(pg);
return 0;
}