简单的动态规划,重点是怎样才算是好的实现。
1 # include <stdio.h>
2
3 # define MAXN 100
4
5 short int a[MAXN][MAXN];
6
7 int main()
8 {
9 int n, i, j;
10
11 scanf("%d", &n);
12
13 for (i = 0; i < n; ++i)
14 for (j = 0; j <= i; ++j)
15 scanf("%d", &a[i][j]);
16
17 for (i = n-1; i > 0; --i)
18 for (j = 0; j <= i; ++j)
19 a[i-1][j] += (a[i][j]>a[i][j+1] ? a[i][j]:a[i][j+1]);
20
21 printf("%d\n", a[0][0]);
22
23 return 0;
24 }
节省内存的做法:
1 # include <stdio.h>
2
3 short int a[100];
4
5 int main()
6 {
7 int n, i, j, t, k, max, u;
8
9 scanf("%d", &n);
10
11 for (i = 0; i < n; ++i)
12 for (t = j = 0; j <= i; ++j)
13 {
14 u = a[j];
15 scanf("%d", &k);
16 a[j] = k + (t>a[j] ? t:a[j]);
17 t = u;
18 }
19
20 max = a[0];
21 for (i = 0; i < n; ++i)
22 if (a[i] > max) max = a[i];
23
24 printf("%d\n", max);
25
26 return 0;
27 }
/* */