提交链接:http://218.5.5.242:9014/problem.asp?id=1168
是个普通的dp问题,以花的idx划分阶段,每个阶段的状态:dp[i][j]表示第i束花,放在第j个花瓶中的max val
每个阶段的状态转移方程: dp[i][j] = max(dp[i-1][k]+val[i][j], dp[i][j]), (0 < k < j)
ans = max(dp[row][i], ans)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 101
int val[MAXN][MAXN], dp[MAXN][MAXN], pre[MAXN][MAXN];
void back_trace(int flower_idx, int vase_idx)
{
if( -1 == vase_idx ) {
return;
}
back_trace(flower_idx-1, pre[flower_idx][vase_idx]);
printf("%d ", vase_idx+1);
}
void dynamic_programming(const int &row, const int &col)
{
int ans(0), idx;
memset(dp, 0, sizeof(dp)); memset(pre, -1, sizeof(pre));
for(int i = 0; i < col; i ++) {
dp[0][i] = val[0][i];
}
for(int i = 1; i < row; i ++) {
for(int j = i; j < col; j ++) {
for(int k = 0; k < j; k ++) {
if( dp[i][j] < dp[i-1][k]+val[i][j] ) {
dp[i][j] = dp[i-1][k]+val[i][j]; pre[i][j] = k;
}
}
}
}
for(int i = row-1; i < col; i ++) {
if( ans < dp[row-1][i] ) {
ans = dp[row-1][i]; idx = i;
}
}
printf("%d\n", ans); back_trace(row-1, idx); printf("\n");
}
int main(int argc, char const *argv[])
{
int row, col;
while( ~scanf("%d %d", &row, &col) ) {
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
scanf("%d", &val[i][j]);
}
}
dynamic_programming(row, col);
}
return 0;
}