Cod sursa(job #2638622)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 29 iulie 2020 10:33:55
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <cstdio>
#include <deque>

using namespace std;

const int NMAX = 5e6 + 5;

int N, K, A[NMAX];

deque < int > D;

namespace InParser
{
static const int BSIZE = (1 << 16);

static int pos = BSIZE - 1;
static char buff[BSIZE];

static inline char Char ()
{
    ++pos;

    if(pos == BSIZE)
    {
        pos = 0;

        int n = fread(buff, 1, BSIZE, stdin);

        if(n != BSIZE)
            for(int i = n; i < BSIZE; ++i)
                buff[i] = 0;
    }

    return buff[pos];
}

inline int Int ()
{
    int sign = 1, ans = 0;

    for( ; ; )
    {
        char Ch = Char();

        if(Ch == '-')
        {
            sign = -1;

            break;
        }

        if(Ch >= '0' && Ch <= '9')
        {
            ans = (int)(Ch - '0');

            break;
        }
    }

    for( ; ; )
    {
        char Ch = Char();

        if(Ch >= '0' && Ch <= '9')
            ans = ans * 10 + (int)(Ch - '0');
        else
            break;
    }

    return (ans * sign);
}
};

static inline void Read ()
{
    ios_base :: sync_with_stdio(false);
    cin.tie(nullptr);

    freopen("deque.in", "r", stdin);
    freopen("deque.out", "w", stdout);

    N = InParser :: Int(), K = InParser :: Int();

    for(int i = 1; i <= N; ++i)
        A[i] = InParser :: Int();

    return;
}

static inline void Solve ()
{
    long long ans = 0;

    for(int i = 1; i <= N; ++i)
    {
        while(!D.empty() && A[i] < A[D.back()])
            D.pop_back();

        D.push_back(i);

        while((i - D.front() + 1) > K)
            D.pop_front();

        if(i >= K)
            ans += 1LL * A[D.front()];
    }

    printf("%lld\n", ans);

    return;
}

int main()
{
    Read();

    Solve();

    return 0;
}