Cod sursa(job #2605778)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 25 aprilie 2020 19:44:32
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

using namespace std;

class InParser
{
private:
    FILE *fin;
    char *buff;
    int sp;

    char read_ch()
    {
        ++sp;
        if(sp==4096)
        {
            sp=0;
            fread(buff,1,4096,fin);
        }
        return buff[sp];
    }

public:
    InParser(const char* nume)
    {
        fin=fopen(nume,"r");
        buff=new char[4096]();
        sp=4095;
    }

    InParser& operator >> (int &n)
    {
        char c;
        while(!isdigit(c=read_ch())&&c!='-');
        int sgn=1;
        if (c=='-')
        {
            n=0;
            sgn=-1;
        }
        else
        {
            n=c-'0';
        }
        while(isdigit(c=read_ch()))
        {
            n=10*n+c-'0';
        }
        n*=sgn;
        return *this;
    }

    InParser& operator >> (long long &n)
    {
        char c;
        n=0;
        while(!isdigit(c=read_ch())&&c!='-');
        long long sgn=1;
        if(c=='-')
        {
            n=0;
            sgn=-1;
        }
        else
        {
            n=c-'0';
        }
        while(isdigit(c=read_ch()))
        {
            n=10*n+c-'0';
        }
        n*=sgn;
        return *this;
    }
};

InParser f("deque.in");
ofstream g("deque.out");

int n, k, x, A[5000005];
long long Sum;
deque < int > DQ;

int main()
{
    f >> n >> k;
    for(int i = 1; i <= n; ++i){
        f >> A[i];
        while(!DQ.empty() && DQ.front() + k <= i) DQ.pop_front();
        while(!DQ.empty() && A[DQ.back()] > A[i]) DQ.pop_back();
        DQ.push_back(i);
        if(i >= k) Sum += 1LL * A[DQ.front()];
    }
    g << Sum;
    return 0;
}