# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1208894 | andrejikus | Boxes with souvenirs (IOI15_boxes) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
//#include "boxes.h"
using namespace std;
typedef long long ll;
void DBG() { cerr << "]" << endl; }
template<class H, class... T> void DBG(H h, T... t) { cerr << to_string(h); if(sizeof...(t)) cerr << ", "; DBG(t...); }
#define dbg(...) cerr << "[" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
static char _buffer[1024];
static int _currentChar = 0;
static int _charsNumber = 0;
static FILE *_inputFile, *_outputFile;
const int N = 1e7 + 3;
const ll inf = 1e18;
ll pref[N], suf[N];
static inline int _read() {
if (_charsNumber < 0) {
exit(1);
}
if (!_charsNumber || _currentChar == _charsNumber) {
_charsNumber = (int)fread(_buffer, sizeof(_buffer[0]), sizeof(_buffer), _inputFile);
_currentChar = 0;
}
if (_charsNumber <= 0) {
return -1;
}
return _buffer[_currentChar++];
}
static inline int _readInt() {
int c, x, s;
c = _read();
while (c <= 32) c = _read();
x = 0;
s = 1;
if (c == '-') {
s = -1;
c = _read();
}
while (c > 32) {
x *= 10;
x += c - '0';
c = _read();
}
if (s < 0) x = -x;
return x;
}
long long delivery(int n, int k, int l, int p[]) {
ll ans = inf;
for (int r = 1; r <= n; r++) {
int ost2 = r%k;
int j = (ost2 == 0 ? k-1 : ost2-1);
suf[j] += l-p[n-r];
}
for (int i = 0; i <= n; i++) {
ll res = 0;
int r = (n-i);
int ost1 = i%k;
int j = (ost1 == 0 ? k-1 : ost1-1);
if (i > 0) {
res += p[i-1];
res += min(p[i-1], l-p[i-1]);
res += 2*pref[j];
pref[j] += p[i-1];
}
//dbg(pref[j], res, i);
int ost2 = r%k;
j = (ost2 == 0 ? k-1 : ost2-1);
if (r > 0) {
suf[j] -= l-p[n-r];
res += (l-p[n-r]);
res += min(l-p[n-r], p[n-r]);
res += 2*suf[j];
}
//dbg(suf[j], res, i, j);
ans = min(ans, res);
}
return ans;
}
int main() {
/*_inputFile = fopen("boxes.in", "rb");
_outputFile = fopen("boxes.out", "w");*/
int N, K, L; cin >> N >> K >> L;
int *p = (int*)malloc(sizeof(int) * (unsigned int)N);
for (int i = 0; i < N; i++) {
cin >> p[i];
}
cout << delivery(N, K, L, p) << "\n";
//fprintf(_outputFile, "%lld\n", delivery(N, K, L, p));
return 0;
}
/*
3 2 8
1 2 5
*/