<h2>Problem Description</h2><div class="pro_desc"><p>Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.</p><center><img src="https://img-blog.csdnimg.cn/2022010621281866998.png" alt="" />
</center><p>In the sample above, the route from 7 to 3 to 8 to 7 to 5 produces the highest sum: 30.</p></div><h2><img src="http://acm.fzu.edu.cn/image/prodesc.gif" alt="" /> Input</h2><div class="pro_desc">There are multiple test cases.The first line of each test case contains R (1 <= R <= 1000), the number of rows. Each subsequent line contains the integers for that particular row of the triangle. All the supplied integers are non-negative and no larger than 100.</div><h2><img src="http://acm.fzu.edu.cn/image/prodesc.gif" alt="" /> Output</h2><div class="pro_desc">Print a single line containing the largest sum using the traversal specified for each test case.</div><h2><img src="http://acm.fzu.edu.cn/image/prodesc.gif" alt="" /> Sample Input</h2><div class="data">5</div><div class="data">7</div><div class="data">3 8</div><div class="data">8 1 0</div><div class="data">2 7 4 4</div><div class="data">4 5 2 6 5</div><h2><img src="http://acm.fzu.edu.cn/image/prodesc.gif" alt="" /> Sample Output</h2><div class="data">30 </div><div>
</div>
//动态规划逆推
# include "stdio.h"
# include <iostream>
# include <algorithm>
using namespace std;
int a[1010][1010];
int p[1010];
int main()
{
int n, j, k;
while(scanf("%d", &n)!=EOF)
{
for(j=1; j<=n; j++)
{
for(k=1; k<=j; k++)
{
scanf("%d", &a[j][k]);
}
}
for(j=1; j<=n; j++)
{
p[j]=a[n][j];
}
for(j=n-1; j>=1; j--)
{
for(k=1; k<=j; k++)
{
p[k]=max(a[j][k]+p[k], a[j][k]+p[k+1]);
}
}
printf("%d\n", p[1]);
}
return 0;
}
//采用stl动态数组vector
# include "stdio.h"
# include <iostream>
# include <algorithm>
# include <vector>
using namespace std;
vector<int> m[1010];
int p[1010];
int main()
{
int n, j, k, num;
while(scanf("%d", &n)!=EOF)
{
for(j=0; j<=n-1; j++)
{
for(k=0; k<=j; k++)
{
scanf("%d", &num);
m[j].push_back(num);
}
}
for(j=0; j<=n-1; j++)
{
p[j]=m[n-1][j];
}
for(j=n-2; j>=0; j--)
{
for(k=0; k<=j; k++)
{
p[k]=max(m[j][k]+p[k], m[j][k]+p[k+1]);
}
}
for(j=0; j<=n-1; j++)
{
vector <int>().swap(m[j]);
}
printf("%d\n", p[0]);
}
return 0;
}
//方法三,记忆化搜索
# include "stdio.h"
# include <iostream>
# include <algorithm>
# include "string.h"
using namespace std;
int a[1010][1010];
int p[1010][1010];
int n;
int d(int i, int j)
{
if(p[i][j]>=0)return p[i][j];
return p[i][j]=a[i][j]+(i==n?0:max(d(i+1, j), d(i+1, j+1)));
}
int main()
{
int j, k;
while(scanf("%d", &n)!=EOF)
{
for(j=1; j<=n; j++)
{
for(k=1; k<=j; k++)
{
scanf("%d", &a[j][k]);
}
}
memset(p, -1, sizeof(p));
printf("%d\n", d(1, 1));
}
return 0;
}