Cod sursa(job #2543495)

Utilizator grotyDan Petri groty Data 11 februarie 2020 10:39:20
Problema Deque Scor 60
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[5000005], st[5000005], dr[500005];

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;
    }
    fout << rez;
    fin.close();
    fout.close();
    return 0;
}