Cod sursa(job #2543491)

Utilizator grotyDan Petri groty Data 11 februarie 2020 10:36:36
Problema Deque Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>
#define INF 2000000000

using namespace std;

ifstream fin("deque.in");
ofstream fout("deque.out");


int a[5000001], st[5000001], dr[500001];

int main()
{
    int n, k;
    fin >> n >> k;
    for(int i = 1; i <= n; i++)
    {
        fin >> a[i];
    }
    st[0] = INF;
    for(int i = 1; i <= n; i++)
    {
        if(i % k == 1)
            st[i] = a[i];
        else
            st[i] = min(st[i - 1], a[i]);
    }
    dr[n + 1] = INF;
    dr[n] = a[n];
    for(int i = n - 1; i >= 1; i--)
        if(i % k == 0)
            dr[i] = a[i];
        else
            dr[i] = min(dr[i + 1], a[i]);

    long long rez = 0;
    int a = 1, b = k;
    while(b <= n)
    {
        rez += min(dr[a], st[b]);
        ++a;
        ++b;
    }
    cout << rez;
    fin.close();
    fout.close();
    return 0;
}