Cod sursa(job #2311039)

Utilizator NToniBoSSNicolae Tonitza NToniBoSS Data 2 ianuarie 2019 16:01:14
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>
#define LIM 1<<17
/// TONI BO$$ was here
/// #MLC

using namespace std;
char BUF[LIM];
int poz;

inline char getChar(){
    poz++;
    if(poz>=LIM){
    	fread(BUF,LIM,1,stdin);
    	poz=0;
    }
    return BUF[poz];
}

inline int getNr(){
    int r=0, semn=1;
    char ch=getChar();
    while(isdigit(ch)==0 && ch!='-') ch=getChar();
    if(ch=='-'){
        semn=-1;
        ch=getChar();
    }
    while(isdigit(ch)!=0){
        r=r*10+semn*(ch-'0');
        ch=getChar();
    }
    return r;
}

int v[5000001],deq[5000001];

int main()
{
    int i,n,p,u,k;
    long long sum;
    freopen("deque.in","r",stdin);
    freopen("deque.out","w",stdout);
    n=getNr();
    k=getNr();
    for(i=1; i<=n; i++)
        v[i]=getNr();
    p=u=1;
    deq[1]=1;
    for(i=2; i<=k; i++)
    {
        while(u>0 && v[i]<v[deq[u]])
            u--;
        deq[++u]=i;
    }
    sum=v[deq[1]];
    for(; i<=n; i++)
    {
        if(deq[p]<i-k+1)
            p++;
        while(u>=p && v[i]<v[deq[u]])
            u--;
        deq[++u]=i;
        sum+=v[deq[p]];
    }
    printf("%lld",sum);

    return 0;
}