Cod sursa(job #2149043)

Utilizator adiaioanaAdia R. adiaioana Data 2 martie 2018 11:46:38
Problema Deque Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("deque.in");
ofstream fout("deque.out");
struct chestie{
long long nr,ind;
}w[5000011];
long long v[5000011],s,n,k,fn,inc;
bool comp(chestie a,chestie b);
int main()
{
    fin>>n>>k;
    for(int i=1;i<=n;i++)
    {
        fin>>v[i];
        if(i<=k)
            w[i].nr=v[i],w[i].ind=i;
    }
    sort(w+1,w+k+1,comp);
    s=w[1].nr;
    inc=1;fn=k;
    for(int i=k+1;i<=n;i++)
    {
        while(fn&&w[fn].nr>v[i])
            fn--;
        w[++fn].nr=v[i];w[fn].ind=i;
        while(i-w[inc].ind>k-1)
            inc++;
        s+=w[inc].nr;
    }
    fout<<s<<'\n';
    return 0;
}
bool comp(chestie a,chestie b)
{
    if(a.nr<b.nr)
        return 1;
    if(a.nr>b.nr)
        return 0;
    if(a.ind<b.ind)
        return 1;
    return 0;
}