Shuta
Time Limit: 1000/1000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Total submission (s): 21314 accepted submission (s): 12808
When Problem description describes the DP algorithm, a classic example is the data tower problem, which is described as follows:
There is a number tower as shown below. It is required to go from the top layer to the bottom layer. If each step can only go to adjacent nodes, what is the maximum sum of the numbers of the nodes that pass through?
I already told you that this is a DP question. Can you AC it?
Input data first includes an integer c, indicating the number of test instances. The first line of each test instance is an integer N (1 <= n <= 100 ), the height of the tower. Next, use N rows of numbers to represent the tower. Row I has an I integer, and All integers are within the range [0, 99.
Output for each test instance, the output may be the largest sum, and the output of each instance occupies one row.
Sample Input
1573 88 1 0 2 7 4 44 5 2 6 5
Sample output
30
Source2006/1/15 ACM Program Design Final Examination
In general, it is an entry-level question of DP, because it is relatively simple to indicate this state equation, from bottom up: DP [I] [J] + = DP [I + 1] [J + 1], DP [I + 1] [J] From top up: DP [I] [J] + = max (DP [I-1] [J-1], DP [I-1] [J]; but from top down, you also need to judge the value of the two boundary, DP [I] [0] + = DP [I-1] [0] when it is at the left boundary; the right boundary is DP [I] [I] + = DP [I-1] [J-1];
The following code is used:
/* Top to bottom */# include <stdio. h> # include <iostream> # define max (A, B) A> B? A: busing namespace STD; int DP [360] [360]; int main () {int T, I, j, N; int maxn; CIN> T; while (t --) {CIN> N; for (I = 0; I <n; I ++) for (j = 0; j <= I; j ++) cin> DP [I] [J]; for (I = 1; I <n; I ++) {DP [I] [0] + = DP [I-1] [0]; DP [I] [I] + = DP [I-1] [I-1];} for (I = 2; I <n; I ++) {for (j = 1; j <I; j ++) DP [I] [J] + = max (DP [I-1] [J-1], DP [I-1] [J]);} For (maxn =-1, j = 0; j <n; j ++) maxn = max (maxn, DP [n-1] [J]); cout <maxn <Endl ;}return 0 ;} /* from bottom to top */# include <Io Stream >#include <cstdio> int DP [1001] [1001]; # define max (A, B) A> B? A: busing namespace STD; int main (int I, Int J) {int t; int N; CIN> T; while (t --) {CIN> N; for (I = 0; I <n; I ++) for (j = 0; j <= I; j ++) CIN> DP [I] [J]; for (I = n-1; I> = 0; I --) for (j = 0; j <= I; j ++) DP [I] [J] + = max (DP [I + 1] [J + 1], DP [I + 1] [J]); cout <DP [0] [0] <Endl;} return 0;} is simpler than that, because it is a fixed point, there is no need to determine whether it is the maximum value. There is also a kind of memory-based search, which is optimized based on dynamic planning.