「Bzoj 1652」「Usaco2006 Feb」Treats for the Cows (区间DP)

BZOJ 1652
Luogu 2858
from: USACO 2006 Feb Sliver(USACO刷题第5题)

显然DP。
设$f[i][j]$为左取$i$个,右取$j$个的最大值
初值:
$$f[x][0] = \sum_{i=1}^{x}vi[i]*i$$
$$f[0][x] = \sum_{i=n}^{x}vi[i]*(i-n+1)$$
方程:
$$f[i][j] = max(f[i-1][j]+(i+j)*vi[i], f[i][j-1]+(i+j)*vi[n-j+1])$$

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
#define ms(i, j) memset(i, j, sizeof i)
#define LL long long
using namespace std;

const int MAXN = 2000 + 5;
int f[MAXN][MAXN], n, vi[MAXN];

void clear() {
}
void init() {
    clear();
    for (int i=1;i<=n;i++) scanf("%d", &vi[i]);
}
void solve() {
    int tot = 0;
    f[0][0] = 0;
    for (int i=1;i<=n;i++) {
        tot += vi[i]*i;
        f[i][0] = tot;
    }
    tot = 0;
    for (int i=n;i>=1;i--) {
        tot += vi[i]*(n-i+1);
        f[0][n-i+1] = tot;
    }
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=n;j++) {
            f[i][j] = max(f[i-1][j]+(i+j)*vi[i], f[i][j-1]+(i+j)*vi[n-j+1]);
        }
    }
    int ans = 0;
    for (int i=0;i<=n;i++) {
        ans = max(f[i][n-i], ans);
    }
    printf("%d\n", ans);
}
int main() {
    #ifndef ONLINE_JUDGE
    freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
    #endif
    while (scanf("%d", &n)==1&&n) init(), solve();
    return 0;
}
------ 本文结束 ------