自己動態規劃的第一題,數字三角形
阿新 • • 發佈:2019-02-08
1087: 三角形
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 72 Solved: 40
[Submit][Status][BBS]
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(圖一)
圖一表示一個5行的數字三角形。假設給定一個n行數字三角形,計算出從三角形頂至底的一條路徑,使該路徑經過的數字總和最大。
每一步只能由當前位置向左下或右下。
Input
你的程式要能接受標準輸入。第一行包含一個整數T,表示總的測試次數。
對於每一種情況:第一行包含一個整數N,其中1 < N < 100,表示三角形的行數。
接下來的N行輸入表示三角形的每一行的元素Ai,j,其中0 < Ai,j < 100。
Output
輸出每次測試的最大值並且佔一行。
Sample Input
1 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5Sample Output
30HINT
程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#include<stdio.h> #include<string.h>
#include<algorithm>
using
namespace
std;
#define
N 105
int
a[N][N];
int
d[N][N];
int
main()
{
int
t;
scanf ( "%d" ,&t);
while (t--)
{
int
n,i,j;
scanf ( "%d" ,&n);
memset (d,0, sizeof (d));
for (i=1;i<=n;i++)
{
for (j=1;j<=i;j++)
{
scanf ( "%d" ,&a[i][j]);
}
}
for (i=1;i<=n;i++)
{
d[n][i]=a[n][i];
}
for (i=n-1;i>=1;i--)
{
for (j=1;j<=i;j++)
{
d[i][j]=a[i][j]+max(d[i+1][j],d[i+1][j+1]);
}
}
printf ( "%d\n" ,d[1][1]);
}
return
0;
}
/**************************************************************
Problem:
1087
User:
14311020312
Language:
C++
Result:
Accepted
Time:1
ms
Memory:1116
kb
****************************************************************/
|