# Yukicoder No.409 ダイエット

,

http://yukicoder.me/problems/no/409

## solution

DP。二次関数は急なので途中で打ち切れて$O(N \sqrt{\frac{\max D_i + A}{B}})$。ただし$B = 0$なら$O(1)$。

## implementation

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))
#define repeat_reverse(i,n) for (int i = (n)-1; (i) >= 0; --(i))
#define whole(f,x,...) ([&](decltype((x)) y) { return (f)(begin(y), end(y), ## __VA_ARGS__); })(x)
typedef long long ll;
using namespace std;
template <class T> void setmin(T & a, T const & b) { if (b < a) a = b; }
const ll inf = ll(1e18)+9;
int main() {
// input
int n, a, b, w; cin >> n >> a >> b >> w;
vector<int> d(n); repeat (i,n) cin >> d[i];
if (b == 0) {
// output
cout << w - a*(ll)n << endl;
} else {
// dp
n += 1;
d.push_back(0);
int limit = 2 * sqrt((*whole(max_element, d) + a) / b) + 3;
vector<ll> dp(n+1);
dp[0] = w;
repeat (i,n) {
ll acc = inf;
repeat_reverse (j,i+1) {
setmin(acc, dp[j] - a *(ll) ll(i-j) + b *(ll) (i-j)*(i-j+1)/2);
if (i-j > limit) break;
}
dp[i+1] = acc + d[i];
}
// output
cout << dp[n] << endl;
}
return 0;
}