用dp[i][j]表示将flower i放在vase j中“这个状态“所能达到的最大美感值,假设flower i放入各个vase中的美感值分别为fv[1]...fv[V],则
for cur = i : V
dp[i][cur] = -INF;
for pre = i-1 : cur-1
dp[i][cur] = max(dp[i-1][pre] + fv[cur], dp[i][cur]);
观察状态转换方程可以看出,我们完全可以边输入边dp省去fv[]数组的开销:
#include <cstdio>
#define NINF -9999
inline short max(short a, short b){ return a > b ? a : b; }
short F, V;
short dp[101][101] = {0};//dp[i][j] stands for flower i put shorto vase j
//thus first i-1 flowers been put shorto first j-1 vases
int main()
{
short i, j, k, beauty;
while(scanf("%d%d", &F, &V) == 2){
//input and dp
for(i = 1; i <= F; ++i){
//flower i can not put into vase 1 ~ vase i-1, so its value is useless
for(j = 1; j < i; ++j) scanf("%d", &beauty);
//dp while input
for(j = i; j <= V; ++j){//put flower i shorto vase j
scanf("%d", &beauty);
dp[i][j] = NINF;
for(k = i - 1; k < j; ++k){//put flower i-1 shorto vase i-1 ~ j-1
dp[i][j] = max(dp[i][j], dp[i-1][k] + beauty);
}
}
}
//print result
beauty = NINF;
for(i = F; i <= V; ++i) beauty = max(beauty, dp[F][i]);
printf("%d\n", beauty);
}
return 0;
}
时间0ms,空间168KB,到这里本应该已经结束了,可是回头再想一想滚动数组,由于dp[i][j]仅与dp[i-1][i-1]~dp[i-1][j-1]有关,保存fv[]后,利用逆向递推的滚动数组,我们实际上可以将两维的dp[][]变为一维的dp[],一下就节省了100*101*2bytes的空间,代码如下:
#include <cstdio>
#define NINF -9999
inline short max(short a, short b){ return a > b ? a : b; }
short F, V;
short fv[101];
short dp[101];
int main()
{
short i, j, k, beauty;
while(scanf("%d%d", &F, &V) == 2){
//initialize(原来两维dp[][]时,边界dp[0][]这一行一直为0不会用到,所以不用单独拉出来初始化)
for(i = 0; i < V; ++i) dp[i] = 0;
//input and dp
for(i = 1; i <= F; ++i){
//input
for(j = 1; j <= V; ++j) scanf("%d", &fv[j]);
//dp in reverse direction
for(j = V; j >= i; --j){//put flower i shorto vase j
dp[j] = NINF;
for(k = i - 1; k < j; ++k){//put flower i-1 shorto vase i-1 ~ j-1
dp[j] = max(dp[j], dp[k] + fv[j]);
}
}
}
//print result
beauty = NINF;
for(i = F; i <= V; ++i) beauty = max(beauty, dp[i]);
printf("%d\n", beauty);
}
return 0;
}
正如预期,空间减少了20K,不过出乎意料的是时间却变成了16ms,看来OJ的测试时间有时候也看RP呢,呵呵