二维DP【洛谷P1508】

题目链接戳这里:https://www.luogu.org/problemnew/show/P1508

很简单的一个题目,完全没难度,但是我为啥要写出来呢,因为刚开始我不会啊!

一直想着怎么从起点往上搜,其实这题根本不需要,我们只需要从最上面往下跑,最后答案会落在起点那三个格子里面的。

代码:
 

#include <bits/stdc++.h>
using namespace std;
const int maxn = 210;
int G[maxn][maxn];
int dp[maxn][maxn];
void init()
{
	memset(G,0,sizeof(G));
	memset(dp,0,sizeof(dp));
}
int main()
{
	int n,m;
	cin>>m>>n;
	int x = m;
	int y = n/2+1;
	init();
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cin>>G[i][j];
		}
	}
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			dp[i][j] = max(max(dp[i-1][j],dp[i-1][j-1]),dp[i-1][j+1])+G[i][j];
		}
	}
	cout<<max(max(dp[x][y-1],dp[x][y]),dp[x][y+1])<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/KIKO_caoyue/article/details/83342261
今日推荐