题目链接:http://hihocoder.com/problemset/problem/1617
题解:一道递推的dp题。这题显然可以考虑两个人同时从起点出发这样就不会重复了设dp[step][i][j]表示走了step步,第一个人在第i行第二个人在第j行第几列就用step减去就行
然后就是简单的递推注意第一个人一定是在第二个人上面的这样才确保不会重复。
#include <iostream>
#include <cstring>
#include <cstdio>
#define inf 0X3f3f3f3f
using namespace std;
int dp[ * ][][];
int a[][] , n;
bool Is(int step , int x , int y) {
int x1 = step - x , y1 = step - y;
return (x1 >= && x1 < n && y1 >= && y1 < n && x >= && x < n && y >= && y < n);
}
int get_val(int step , int x , int y) {
if(Is(step , x , y)) return dp[step][x][y];
return -inf;
}
int main() {
scanf("%d" , &n);
for(int i = ; i < n ; i++) {
for(int j = ; j < n ; j++) {
scanf("%d" , &a[i][j]);
dp[][i][j] = -inf;
}
}
dp[][][] = a[][];
for(int step = ; step <= * n - ; step++) {
for(int i = ; i < n ; i++) {
for(int j = i ; j < n ; j++) {
dp[step][i][j] = -inf;
if(!Is(step , i , j)) continue;
if(i != j) {
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i - ,j - ));
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i - , j));
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i , j - ));
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i , j));
dp[step][i][j] += a[i][step - i] + a[j][step - j];
}
else {
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i - , j - ));
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i - , j));
dp[step][i][j] = max(dp[step][i][j] , get_val(step - , i , j));
dp[step][i][j] += a[i][step - i];
//这里将他们到达同一点时val就取一次那么最大值肯定不是去走同一点的。
}
//这里的转移至要注意第一个人一定在第二个人上面就行,也就是说i>=j是必须的转移时也要注意
}
}
}
printf("%d\n" , dp[ * n - ][n - ][n - ] + a[][] + a[n - ][n - ]);
return ;
}