7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers 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.
碎碎念:這道題最開始的時候想的過於複雜,思路邏輯都不好,在自己思考以及別人提示的情況下花了一兩個小時把它編程實現。
這次是第二次看這道題,思路很直觀,很直接。算法很大程度成應該都是在模擬人的思維思路。所以很簡單考慮一下自己對於這道題會怎麼算就好了。
思路:思路很直接,從第一層算到最後一層,再比較最後一層,得出最大的結果。
如第一層加到第二層上,第二層從 3 8,變爲10 15,第二層從8 1 0,變爲18 16 15(對於第三層原本的1,應在比較後加第二層的較大一個),第四層爲20 25 20 19,第五層爲 24 30 27 26 24。 再比較最後一行得出結果爲30。
代碼如下:
#include<stdio.h>
#include<iostream>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
///聲明數組
int **p=NULL;
p=new int*[n];
for(int i=0;i<n;i++)
{
p[i]=new int [i+1];
}
///輸入數組
for(int i=0;i<n;i++)///每一行
{
for(int j=0;j<=i;j++)///每一列
{
scanf("%d",&p[i][j]);
}
}
//判斷數組
for(int i=1;i<n;i++)///每一行
{
for(int j=0;j<=i;j++)///每一列
{
if (j == 0)
p[i][j] += p[i - 1][0];
else if (j == i)
p[i][j] +=p[i - 1][j - 1];
else
{
if (p[i - 1][j - 1] >= p[i - 1][j])
p[i][j] +=p[i - 1][j - 1];
else
p[i][j] += p[i - 1][j];
}
}
}
//找出最後一行的最大值
int max = p[n-1][0];
for (int j = 1; j<n; j++)
{
if (max<p[n-1][j])
max = p[n-1][j];
}
printf("%d\n", max);
}
}