HDU_3506
由于是环,所以可以先把序列copy一份,然后写出状态转移方程f[i][j]=min{f[i][k-1]+f[k][j]}+w[i][j],其中w为i到j的time和,这个和黑书上讲四边形不等式时候的状态转移方程是一样的,因而只要证明出w为凸即可。而因为w[i][j]+w[i+1][j+1]==w[i][j+1]+w[i+1][j],所以w为凸,这时就可以放心地用四边形不等式优化dp了。
#include<stdio.h>
#include<string.h>
#define MAXD 2010
#define INF 0x3f3f3f3f
int N, f[MAXD][MAXD], K[MAXD][MAXD], A[MAXD], a[MAXD];
void init()
{
int i, j, k;
A[0] = 0;
for(i = 0; i < N; i ++)
{
scanf("%d", &a[i]);
A[i] = A[i - 1] + a[i];
}
for(i = N; i < 2 * N; i ++)
A[i] = A[i - 1] + a[i - N];
}
int getw(int i, int j)
{
return A[j] - A[i - 1];
}
int getmin(int x, int y)
{
return x < y ? x : y;
}
void solve()
{
int i, j, k, p, t, ans;
for(i = 0; i <= 2 * N; i ++)
{
f[i][i] = 0;
K[i][i] = i;
}
for(p = 1; p < N; p ++)
for(i = 1; (j = i + p) <= 2 * N; i ++)
{
f[i][j] = INF;
for(k = K[i][j - 1]; k <= K[i + 1][j]; k ++)
{
t = f[i][k - 1] + f[k][j] + getw(i, j);
if(t < f[i][j])
{
f[i][j] = t;
K[i][j] = k;
}
}
}
ans = INF;
for(i = 1; i <= N; i ++)
ans = getmin(f[i][i + N - 1], ans);
printf("%d\n", ans);
}
int main()
{
while(scanf("%d", &N) == 1)
{
init();
solve();
}
return 0;
}