棋盘型动态规划 之 CODE[VS] 1220 数字三角形
/*
dp[i][j] := 从顶点到达点(i,j)时,所走路径上的最大值
初始化:
dp[][] = {-INF} // 测试数据有负数,所以初始值 dp[][] = -INF
dp[1][1] = arr[1][1]
状态方程:
dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + arr[i][j]
答案:
max{ dp[N][i] }
0 <= i <= N-1
*/
1 #define _CRTDBG_MAP_ALLOC 2 #include <stdlib.h> 3 #include <crtdbg.h> 4 #define _CRT_SECURE_NO_WARNINGS 5 #define HOME 6 7 #include <iostream> 8 #include <cstdlib> 9 #include <cstdio> 10 #include <cstddef> 11 #include <iterator> 12 #include <algorithm> 13 #include <string> 14 #include <locale> 15 #include <cmath> 16 #include <vector> 17 #include <cstring> 18 using namespace std; 19 const int INF = 0x3f3f3f3f; 20 const int MaxN = 30; 21 const int Max = 110; 22 23 int N; 24 int arr[Max][Max]; 25 int dp[Max][Max]; 26 27 bool Check(int x, int y, int len) 28 { 29 if ((x<=0) || (y<=0) || (y>len)) 30 { 31 return false; 32 } 33 return true; 34 } 35 36 void Solve() 37 { 38 int x1, y1, x2, y2; 39 dp[1][1] = arr[1][1]; 40 for (int i = 1; i <= N; ++i) 41 { 42 for (int j = 1; j <= i; ++j) 43 { 44 x1 = i - 1; 45 y1 = j - 1; 46 x2 = i - 1; 47 y2 = j; 48 if (Check(x1, y1, i - 1)) 49 { 50 dp[i][j] = max(dp[i][j], dp[x1][y1] + arr[i][j]); 51 } 52 if (Check(x2, y2, i - 1)) 53 { 54 dp[i][j] = max(dp[i][j], dp[x2][y2] + arr[i][j]); 55 } 56 } 57 } 58 /*for (int i = 1; i <= N; ++i) 59 { 60 for (int j = 1; j <= i; ++j) 61 { 62 cout << "(" << i << "," << j << ") : " << dp[i][j] << endl; 63 } 64 }*/ 65 cout << *max_element(dp[N], dp[N] + N + 1) << endl; 66 } 67 68 int main() 69 { 70 #ifdef HOME 71 freopen("in", "r", stdin); 72 //freopen("out", "w", stdout); 73 #endif 74 for (int i = 0; i < Max; ++i) 75 { 76 for (int j = 0; j < Max; ++j) 77 { 78 dp[i][j] = -INF; 79 } 80 } 81 82 83 cin >> N; 84 for (int i = 1; i <= N; ++i) 85 { 86 for (int j = 1; j <= i; ++j) 87 { 88 cin >> arr[i][j]; 89 } 90 } 91 Solve(); 92 93 #ifdef HOME 94 cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl; 95 _CrtDumpMemoryLeaks(); 96 system("pause"); 97 #endif 98 return 0; 99 }