http://acm.hdu.edu.cn/showproblem.php?pid=2845
输入数据数量很大,思考发现可以压缩为一位数组来输入和动态规划,详看代码。
解题思路:
两次dp,先按照每一行dp,再将dp的值dp。dp[i] = max(dp[i-2]+a[i], dp[i-1])。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 200010;
const int INF = 0x3f3f3f3f;
int dp[MAX],b[MAX],a[MAX];
int main(){
// freopen("in.txt", "r", stdin);
int n,m;
while(scanf("%d%d",&n,&m) == 2){
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++)
scanf("%d",&a[j]);
dp[1] = a[1];
for(int j=2; j<=m; j++)
dp[j] = max(dp[j-2]+a[j], dp[j-1]);
b[i] = dp[m];
}
dp[1] = b[1];
for(int i=2; i<=n; i++)
dp[i] = max(dp[i-2]+b[i], dp[i-1]);
printf("%d\n",dp[n]);
}
return 0;
}