[Solution]
Long time not writing anything.
It seems like a DP problem, and it actually is. We can easily come up with the equation that
f[i] = min(f[j] + (j - i) * (j - i - 1) / 2) + a[i]
f[i] means the lowest cost setting a defence tower at the ith position.
That equation means O(n^2) time of state transferring. However, we can simplify it into this
i * j - i * (i - 1) / 2 - a[i] + f[i] = f[j] + j * (j + 1) / 2
That's a equation that wew can set the right part as Y and j as X. We need to find the minimal f[i], which means the intercept of the function should be minimal. That's obviously a DP optimized by slope.
[Code]
#include <cstdio>
#include <memory.h>
#include <ctype.h>
#include <algorithm>
using namespace std;
typedef long double llf;
typedef long long qw;
#ifdef WIN32
#define lld "%I64d"
#else
#define lld "%lld"
#endif
#define _l (qw)
int nextInt() {
int d, s = 0;
do
d = getchar();
while (!isdigit(d));
do
s = s * 10 + d - 48, d = getchar();
while (isdigit(d));
return s;
}
const int maxn = 1000010;
int n, a[maxn], q[maxn], hd, tl;
qw f[maxn], ans;
inline qw gety(int x) {
return f[x] + _l x * (x + 1) / 2;
}
inline llf getk(int i, int j) {
return ((llf)gety(j) - gety(i)) / ((llf)j - i);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
n = nextInt();
for (int i = 0; i < n; i ++)
a[n - i - 1] = nextInt();
f[0] = a[0];
hd = 0, tl = 1;
q[hd] = 0;
ans = a[0] + _l n * (n - 1) / 2;
for (int i = 1; i < n; i ++) {
while (hd + 2 < tl && getk(q[hd], q[hd + 1]) < (llf)i)
hd ++;
f[i] = gety(q[hd]) - _l i * q[hd] + _l i * (i - 1) / 2 + a[i];
ans = min(ans, f[i] + (_l n - i) * (_l n - i - 1) / 2);
q[tl] = i;
while (hd + 2 <= tl && getk(q[tl - 1], q[tl]) < getk(q[tl - 2], q[tl - 1]))
q[tl - 1] = q[tl], tl --;
tl ++;
}
printf(lld "\n", ans);
}