#include #include #include #include #include #include using namespace std; long long solve(int n, int k, int *a) { if (k == 1) return a[0]; if (2 * k > n) return a[k-1]; set > S, T; set U; auto dump = [&]() -> void { cerr << "S = "; for (auto [x, y] : S) cerr << "(" << x << ", " << y << "); "; cerr << endl; cerr << "T = "; for (auto [x, y] : T) cerr << "(" << x << ", " << y << "); "; cerr << endl; cerr << "U = "; for (int u : U) cerr << u << ' '; cerr << endl; }; int segmin[n]; for (int m = 1; m * (k - 1) < n; m++) segmin[m] = *min_element(a + (m-1) * (k-1) + 1, a + m * (k - 1) + 1); int sufmin[n]; sufmin[n-1] = a[n-1]; for (int i = n-2; i >= 0; i--) sufmin[i] = min(sufmin[i+1], a[i]); for (int i = k; i < n; i++) S.insert({a[i], i}); for (int i = 0; i < 2; i++) { U.insert(S.begin()->second); T.insert(*S.begin()); S.erase(S.begin()); } long long sum = 0; for (auto &[val, idx] : T) sum += val; long long ans = a[k-1]; for (int i = 0, m = 2; m * k <= n; m++) { int c = 0; long long tmp = sum; if (*U.begin() > m * (k - 1)) { c++; tmp += segmin[m]; // cerr << "left " << tmp << endl; } if (*U.rbegin() < m*k-1) { c++; tmp += sufmin[m*k-1]; // cerr << "right " << tmp << endl; } if (c > 0) tmp -= T.rbegin()->first; if (c > 1) tmp -= next(T.rbegin())->first; ans = min(ans, tmp); // dump(); // cerr << "m = " << m << " => " << tmp << "; sum = " << sum << "; c = " << c << endl; if ((m + 1) * k > n) break; c = 1; for (int i = (m-1)*(k-1)+1; i <= m*(k-1); i++) { if (U.find(i) != U.end()) { c++; sum -= a[i]; T.erase({a[i], i}); U.erase(i); } else S.erase({a[i], i}); } while (c--) { auto it = S.begin(); sum += it->first; T.insert(*it); U.insert(it->second); // cerr << "add " << it->first << " " << it->second << endl; S.erase(it); } } return ans; } int main() { int n, k; cin >> n >> k; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; cout << solve(n, k, a) << endl; }