题目链接。这个题目很简单,于是很快就1次过了。DP问题。
直接给出状态转移方程:
dpRes[i][j] = max(dpRes[i-1][j-1], dpRes[i-1][j])+A[i][j]
dpRes[i][j]表示前i行第j个数包含在内的最大和,A[i][j]为题目给的三角形(矩阵)。扫描对于最后一行得出最大值即为题目所求。为了节省时间,在输入完成一行后就直接计算出这一行当dpRes[i][j],(for j=1 to i)。我的代码如下:
1: #include <iostream>
2: using namespace std;
3: const int ROW_SIZE = 101;
4: int dpRes[ROW_SIZE][ROW_SIZE];
5: int triangle[ROW_SIZE][ROW_SIZE];
6:
7: int main()
8: {
9: int row=0;
10: cin >> row;
11: if (row<=0 || row>=ROW_SIZE)
12: return -1;
13: for (int i=1; i<=row; i++)
14: {
15: for (int j=1; j<=i; j++)
16: cin >> triangle[i][j];
17: for (int j=1; j<=i; j++)
18: {
19: int temp = dpRes[i-1][j-1]>dpRes[i-1][j] ? dpRes[i-1][j-1] : dpRes[i-1][j];
20: dpRes[i][j] = temp + triangle[i][j];
21: }
22: }
23: int max=0;
24: for (int j=1; j<=row; j++)
25: max = max<dpRes[row][j] ? dpRes[row][j] : max;
26: cout << max << endl;
27: return 0;
28: }