Cod sursa(job #1553509)

Utilizator justsomedudePalade Thomas-Emanuel justsomedude Data 19 decembrie 2015 22:55:33
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include<iostream>
#include<fstream>
#define nmax 5000009
using namespace std;
ifstream fin ("deque.in");
ofstream fout ("deque.out");

struct coord{
    int val, poz;
};

int st, dr, k, n;
coord coada[nmax];
long long int suma;

int main ()
{
    int i, j, x;
    fin >> n >> k >> x;
    st = dr = 1;
    coada[st].val = x;
    coada[st].poz = 1;

    for (i=2; i<=n; i++)
    {
        fin >> x;
        if (coada[st].poz < i-k+1) st++;

        if (st > dr) dr++;
        else
        {
            while (st<=dr && x < coada[dr].val)
                dr--;

            if (st > dr) dr = st;
            else         dr++;
        }
        coada[dr].poz = i;
        coada[dr].val = x;
        if (i>=k) suma += coada[st].val;
    }

    fout << suma << "\n";
    fin.close();
    fout.close();
    return 0;
}