Cod sursa(job #2769385)

Utilizator avtobusAvtobus avtobus Data 15 august 2021 09:26:58
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int INF = 2e7;
struct dstack {
  void push(int x) { r.push({x, std::min(x, rmin())}); }
  void pop() {
    if (l.empty()) {
      while(!r.empty()) {
        int x = r.top().first; r.pop();
        l.push({x, std::min(x, lmin())});
      }
    }
    l.pop();
  }
  stack<pii> l, r;
  bool empty() {
    return l.empty() && r.empty();
  }
  int rmin() { return r.empty() ? INF : r.top().second; }
  int lmin() { return l.empty() ? INF : l.top().second; }
  int min() { return std::min(lmin(), rmin()); }
};

int main(void) {
  freopen("deque.in", "r", stdin);
  freopen("deque.out", "w", stdout);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);
  int N, k;
  cin >> N >> k;
  vi a(N);
  rep(i, N) { cin >> a[i]; }
  dstack st;
  ll ans = 0;
  rep(i, k-1) { st.push(a[i]); }
  for(int i = k-1; i < N; i++) {
    st.push(a[i]);
    ans += st.min();
    st.pop();
  }
  cout << ans << "\n";


  return 0;
}