SGU104 DP

    题意:N行M列的格子,每个格子有一些分值(可能为负),每行取一个格子,使得选取的总分值最大。要求每行所取的格子的列号严格大于上一行。

    Problem:Give you a matrix of N rows and M columns, each grid has a value(maybe negative). You pick only one grid in each row to make the sum of value maximum. It requires that the column number of selected grid must greater than the grid in the last row.

    解法:看到这种题很自然的就往DP方向想。设dp[i][j]为取i行j列的格子时的最大分值,则状态转移方程为dp[i][j] = MAX{dp[i-1][k] + a[i][j]} (i-1<=k<=j-1),表示由前面的一些状态加上a[i][j]得到当前状态最优。最后扫描dp[N][N]到dp[N][M]得到全局最优即可。

    Solution:It's natural to go into the direction of DP when seeing this type of problems. We assume d[i][j] represents the max value when picking the grid in row i and column j. It comes from former legal states that can pick the grid. In the end, scan dp[N][N] to dp[N][M] to get the global optimum.

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
#define inf 1001000
int dp[200][200],f[200][200],a[200][200],n,m,cnt,b[200];
void work(int dep, int tt) {
     if (dep==0) return;
     b[++cnt] = tt;
     work(dep-1,f[dep][tt]);
}     
int main() {
    while (~scanf("%d%d",&n,&m)) {
          for (int i=1;i<=n;i++)
              for (int j=1;j<=m;j++)
                  scanf("%d",&a[i][j]);
          memset(dp,0,sizeof(dp));
          memset(f,0,sizeof(f));
          for (int i=1;i<=n;i++)
              for (int j=i;j<=m;j++) {
                  int tt, tmp = -inf;
                  for (int k=i-1;k<=j-1;k++)
                      if (dp[i-1][k]+a[i][j]>tmp) {
                         tmp = dp[i-1][k]+a[i][j];
                         tt = k;
                      }
                  dp[i][j] = tmp;
                  f[i][j] = tt;
              }
          int tt, ans = -inf;
          for (int i=n;i<=m;i++)
              if (dp[n][i]>ans) {
                         ans = dp[n][i];
                         tt = i;
                      }
          printf("%d\n",ans);
          cnt = 0;
          work(n,tt);
          for (int i=cnt;i>1;i--)
              printf("%d ",b[i]);
          printf("%d\n",b[1]);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值