简单dp之递推(1)--CF 429B B.Working out
2017-08-31 13:52
393 查看
题目链接:
CF 429B B.Working out题目输入输出:
InputThe first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).OutputThe output contains a single number — the maximum total gain possible.
ExamplesInput
3 3 100 100 100 100 1 100 100 100 100Output
800NoteIahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].
题意:
给出n*m的矩阵,每个格子有个数,A从(1,1)出发只能向下或右走,终点为(n,m),B从(n,1)出发只能向上或右走,终点为(1,m)。两个人的速度不一样,走到的格子可以获的该格子的数,两人相遇的格子上的数两个人都不能拿。已知两个人的路径会并且只会相交于某个点,问两个人经过路径上的数的和最大的情况下最大和是多少?思路:
首先要保证只有一个格子重合,那么只可能是以下两种情况:(1) A向右走,相遇后继续向右走,而B向上走,相遇后继续向上走
(2) A向下走,相遇后继续向下走,而B向右走,相遇后继续向右走
接着枚举相遇的格子(i,j)(枚举时注意不可能在四个角相遇),就是考虑四个方向的dp:
dp1[i][j] = 从 (1, 1) 到 (i, j) 的最大分数
dp2[i][j] = 从 (i, j) 到 (n, m) 的最大分数
dp3[i][j] = 从 (n, 1) 到 (i, j) 的最大分数
dp4[i][j] = 从 (i, j) 到 (1, m) 的最大分数
代码:
#include <stdio.h> #include <algorithm> #define M 1002 using namespace std; int mpt[M][M]; int dp1[M][M]; int dp2[M][M]; int dp3[M][M]; int dp4[M][M]; int main() { int n,m,i,j; while(scanf("%d %d",&n,&m)!=EOF) { for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%d",&mpt[i][j]); } } //以下就是四个方向的dp dp1[0][1]=dp1[1][0]=0; //注意初始化 for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { dp1[i][j]=mpt[i][j]+max(dp1[i-1][j],dp1[i][j-1]); } } dp2 [0]=dp2[n+1][1]=0; for(i=n;i>=1;i--) { for(j=1;j<=m;j++) { dp2[i][j]=mpt[i][j]+max(dp2[i][j-1],dp2[i+1][j]); } } dp3[0][m]=dp3[1][m+1]=0; for(i=1;i<=n;i++) { for(j=m;j>=1;j--) { dp3[i][j]=mpt[i][j]+max(dp3[i-1][j],dp3[i][j+1]); } } dp4[n+1][m]=dp4 [m+1]=0; for(i=n;i>=1;i--) { for(j=m;j>=1;j--) { dp4[i][j]=mpt[i][j]+max(dp4[i+1][j],dp4[i][j+1]); } } int ans=-1; for(i=2;i<n;i++) { for(j=2;j<m;j++) { ans=max(ans,dp1[i][j-1]+dp4[i][j+1]+dp2[i+1][j]+dp3[i-1][j]); ans=max(ans,dp1[i-1][j]+dp4[i+1][j]+dp2[i][j-1]+dp3[i][j+1]); } } printf("%d\n",ans); } return 0; }
相关文章推荐
- bzoj 2431 简单dp/递推
- [dp] Codeforces 429B B. Working out(动态规划(DP))
- HD 2048 数塔 DP(简单递推)
- dp的简单递推笔记1
- (CF 148D Bag of mice)<简单概率DP>
- codeforces 429B B. Working out(dp)
- POJ 2441 Arrange the Bulls 状态压缩递推简单题 (状态压缩DP)
- poj 1157 简单递推dp
- Codeforces 429B B. Working out (DP)
- hdu 5965(dp递推,简单题)
- CF 445A 简单DP
- [蓝桥杯] 算法训练 未名湖边的烦恼(dp递推或简单dfs)
- CF 590D Top Secret Task【dp递推+滚动数组】【好题】
- HDU Tickets(简单的dp递推)
- 递推关系的运用加简单DP【UVA11137Ingenuous Cubrency】-------2015年1月27日
- cf 429B Working out(简单dp)
- CF 467C - George and Job (简单区间DP)
- CF 148D Bag of mice 概率dp 简单题
- 简单dp之递推(2)--ZOJ 3747
- codeforces 429B B. Working out 详解(dp)