SGU104 DP

来源:互联网 发布:mac book 复制 编辑:程序博客网 时间:2024/05/16 14:05

    题意: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 1001000int 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;}