Cod sursa(job #2033653)

Utilizator Fanika123Tanasa Stefan Fanika123 Data 7 octombrie 2017 09:42:05
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define in "deque.in"
#define out "deque.out"
using namespace std;
ifstream fin(in);
ofstream fout(out);

deque <int> q;
int a[5000003];
int n,k;
long long s;

void Citire()
{
    int i;

    fin >> n >> k;
    for (i = 1; i <= n; i++)
        fin >> a[i];
}

void Rezolvare()
{
    int i;
    int x;

    /// prelucrez primele k elemente
    for (i = 1; i <= k; i++)
    {
        x = a[i];

        while (!q.empty() && a[q.back()] >= x)
            q.pop_back();

        q.push_back(i);
    }

    s += a[q.front()];

    /// prelucrez restul elementelor
    for (i = k+1; i <= n; i++)
    {
        x = a[i];

        while (!q.empty() && a[q.back()] >= x)
            q.pop_back();

        q.push_back(i);

        /// veriric daca elementul s-a invechit
        if (i - q.front() >= k) q.pop_front();

        s += a[q.front()];
    }

    fout << s << "\n";
}

int main()
{
    Citire();
    Rezolvare();

    fin.close();
    fout.close();
    return 0;
}