您的位置:首页 > 其它

简单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 100
Output
800
NoteIahub 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  CF-429B-B dp