#include #define REP(i, n) for (int i = 0; (i) < (int)(n); ++(i)) #define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i)) #define REP_R(i, n) for (int i = (int)(n)-1; (i) >= 0; --(i)) #define REP3R(i, m, n) for (int i = (int)(n)-1; (i) >= (int)(m); --(i)) #define ALL(x) ::std::begin(x), ::std::end(x) using namespace std; template using reversed_priority_queue = priority_queue, greater >; int64_t solve(int n, int64_t k, const vector& a) { if (k == 1) return a[0]; vector min_a(n + 1, INT64_MAX); REP_R (i, n) { min_a[i] = min(min_a[i + 1], a[i]); } int64_t ans = INT64_MAX; priority_queue > que; int64_t sum_que = 0; set indices_que; reversed_priority_queue > revque; REP3R (i, k - 1, n) { int q = i / (k - 1); int r = i % (k - 1); int m = q + (not not r) - 1; if (k * (m + 1) <= n and m <= que.size() + revque.size()) { while (not que.empty() and ((que.size() > m) or (not revque.empty() and que.top().first > revque.top().first))) { int j = que.top().second; que.pop(); sum_que -= a[j]; indices_que.erase(j); revque.emplace(a[j], j); } while (que.size() < m) { assert (not revque.empty()); int j = revque.top().second; revque.pop(); que.emplace(a[j], j); sum_que += a[j]; indices_que.insert(j); } assert (que.size() == m); if (not indices_que.empty() and *indices_que.rbegin() < k * m) { int j = que.top().second; ans = min(ans, a[i] + sum_que - a[j] + min_a[k * m]); } else { ans = min(ans, a[i] + sum_que); } } que.emplace(a[i], i); sum_que += a[i]; indices_que.insert(i); } return ans; } // generated by online-judge-template-generator v4.7.1 (https://github.com/online-judge-tools/template-generator) int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); constexpr char endl = '\n'; int64_t N; int64_t K; cin >> N; vector A(N); cin >> K; REP (i, N) { cin >> A[i]; } auto ans = solve(N, K, A); cout << ans << endl; return 0; }