POJ 1163:The Triangle
2016-10-27 00:12
381 查看
Description
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5 (Figure 1)
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.Output
Your program is to write to standard output. The highest sum is written as an integer.Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
题解:最基础的dp,直接记录状态
dp[i][j]表示以第i行第j列开头的三角形的最大值
dp[i][j]=max(dp[i+1][j],dp[i+1][j+1])+a[i][j];
(1) 从后向前递推
#include<iostream> #include<algorithm> using namespace std; const int MAXN = 1001; int dp[MAXN][MAXN]; int main() { int n; cin >> n; for (int i = 0; i < n;i++) for (int j = 0; j <= i; j++) cin >> dp[i][j]; for (int i = n - 2; i >= 0;i--) for (int j = 0; j <= i; j++) { dp[i][j] = max(dp[i+1][j],dp[i+1][j+1]) + dp[i][j]; } cout << dp[0][0]; return 0; }
(2) 从前向后递推
#include<iostream> #include<algorithm> using namespace std; const int MAXN = 1001; int dp[MAXN][MAXN]; int main() { int n; cin >> n; for (int i = 0; i < n;i++) for (int j = 0; j <= i; j++) cin >> dp[i][j]; for (int i = 0; i < n;i++) for (int j = 0; j <= i; j++) { if (i==0)continue; else if (j == 0)dp[i][j] = dp[i-1][j] + dp[i][j]; else if (j == i)dp[i][j] = dp[i-1][j-1] + dp[i][j]; else dp[i][j] = max(dp[i-1][j],dp[i-1][j-1]) + dp[i][j]; } int ans = 0; for (int j = 0; j < n; j++) ans = max(ans,dp[n-1][j]); cout << ans; return 0; }
相关文章推荐
- poj 1163 The Triangle
- DP专题1 POJ 1163 The Triangle
- POJ-1163-The Triangle
- POJ1163 The Triangle【DFS】
- POJ 1163 The Triangle【dp+杨辉三角加强版(递归)】
- POJ 1163 The Triangle
- The Triangle - POJ 1163 水题
- POJ1163 The Triangle
- POJ 1163 The Triangle
- POJ 1163 The Triangle
- POJ_1163_The triangle
- POJ 3176-Cow Bowling/POJ 1163-The Triangle(简单DP-数塔)
- poj1163 The Triangle ——DP入门题
- poj 1163 The Triangle【dp】
- POJ 1163:The Triangle(动态规划)
- POJ-1163-The Triangle
- POJ 1163 The Triangle
- poj 1163 The Triangle
- POJ 1163 The Triangle
- POJ-1163-The Triangle (动态规划1)