1. 程式人生 > >hihocoder #1617 : 方格取數(dp)

hihocoder #1617 : 方格取數(dp)

div code 轉移 spa != 同時 space 人在 兩個

題目鏈接: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[2 * 233][233][233]; int a[233][233] , n; bool Is(int step , int x , int y) { int x1 = step - x , y1 = step - y; return (x1 >= 0 && x1 < n && y1 >= 0 && y1 < n && x >= 0 && x < n && y >= 0 && 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 = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++) { scanf("%d" , &a[i][j]); dp[0][i][j] = -inf; } } dp[
0][0][0] = a[0][0]; for(int step = 1 ; step <= 2 * n - 2 ; step++) { for(int i = 0 ; 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 - 1 , i - 1 ,j - 1)); dp[step][i][j] = max(dp[step][i][j] , get_val(step - 1 , i - 1 , j)); dp[step][i][j] = max(dp[step][i][j] , get_val(step - 1 , i , j - 1)); dp[step][i][j] = max(dp[step][i][j] , get_val(step - 1 , 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 - 1 , i - 1 , j - 1)); dp[step][i][j] = max(dp[step][i][j] , get_val(step - 1 , i - 1 , j)); dp[step][i][j] = max(dp[step][i][j] , get_val(step - 1 , i , j)); dp[step][i][j] += a[i][step - i]; //這裏將他們到達同一點時val就取一次那麽最大值肯定不是去走同一點的。 } //這裏的轉移至要註意第一個人一定在第二個人上面就行,也就是說i>=j是必須的轉移時也要註意 } } } printf("%d\n" , dp[2 * n - 2][n - 1][n - 1] + a[0][0] + a[n - 1][n - 1]); return 0; }

hihocoder #1617 : 方格取數(dp)