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;}
- SGU104 DP
- 【DP】sgu104
- SGU104 二维dp
- SGU104
- Sgu104
- SGU104
- sgu104
- SGU104 Little Shop of Flowers (DP)
- SGU104 Little shop of flowers(DP)
- SGU104 Little shop of flowers (DP)
- POJ 1157/SGU104 Little shop of flowers(DP)
- sgu104-动态规划
- sgu104:Little Shop of Flowers
- SGU104 Little Shop of Flowers
- sgu104: Little Shop of Flowers
- SGU104 Little shop of flowers
- SGU水题大集合 SGU104 SGU105 SGU107
- dp
- typedef 函数指针
- linux c++ 多线程 互斥访问
- servlet中获取jsp中的空值问题
- CentOS安装PostGIS
- system troubleshooting
- SGU104 DP
- linux编译ffmjpg和x264总结
- 常见的各种操作延迟时间
- visual studio 2013 Entity Framework 6 MVC 5 体验(一)修改默认数据库,增加自定义字段
- Ubuntu12.04LTS gcc g++版本设置
- 關於Cross Join 和 Outer/Cross Apply
- ibatis入门示例
- Windows 7 系统 优化、调整、恢复(兼SSD优化)
- C++ 中string.find() 函数的用法总结