Cod sursa(job #2666246)

Utilizator AlexNicuNicu Alexandru AlexNicu Data 1 noiembrie 2020 11:52:46
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>

using namespace std;
int deq[8388608], front1, back1, arr[5000001];
void push_front1( int val ) {
  deq[front1] = val;
  front1 = ( front1 - 1 + 8388608 ) % 8388608;
}
void push_back1( int val ) {
  deq[back1] = val;
  back1 = ( back1 + 1 ) % 8388608;
}
void pop_front1() {
  front1 = ( front1 + 1 ) % 8388608;
}
void pop_back1() {
  back1 = ( back1 - 1 + 8388608 ) % 8388608;
}
ifstream cin ( "deque.in" );
ofstream cout ( "deque.out" );
int main()
{
    int i, n, k;
    long long sum;
    cin >> n >> k;
    front1 = back1 = 0;
    for ( i = 1; i <= n; i++ )
      cin >> arr[i];
    for ( i = 1; i <= k; i++ ) {
       while ( front1 != back1 && arr[i] <= arr[deq[( back1 - 1 + 8388608 ) % 8388608]] )
        pop_back1();
       push_back1(i);
    }
    sum = 0;
    for ( ; i <= n; i++ ) {
      sum += (long long)arr[deq[front1]];
      while ( front1 != back1 && deq[front1] <= i - k )
        pop_front1();
      while ( front1 != back1 && arr[i] <= arr[deq[( back1 - 1 + 8388608 ) % 8388608]] )
        pop_back1();
      push_back1(i);
    }
    sum += (long long)arr[deq[front1]];
    cout << sum;
    return 0;
}