Stone Merge (a) time limit: 1000 MS | memory limit: 65535 kb difficulty: 3
-
Description
-
There are n piles of stones in a row, each pile of stones has a certain number. Now we want to build n piles of stones into a pile. The merge process can only pile the adjacent two piles of stones into a pile each time, the cost of each merge is the sum of the two piles of stones, after the N-1 merge into a pile. Obtain the minimum total cost.
-
Input
-
There are multiple groups of test data, input to the end of the file.
The first line of each group of test data has an integer N, indicating that there are n piles of stones.
The next row contains N (0 <n <200) numbers, which respectively indicate the number of N stones separated by spaces.
-
Output
-
The minimum value of the total output cost, which occupies a single row.
-
Sample Input
-
31 2 3713 7 8 16 21 4 18
-
Sample output
-
9239
AC code:
# Include <stdio. h> # include <string. h> # define INF 2000000005int DP [203] [203], sum [203] = {0}; int dp (INT left, int right) {If (DP [left] [right]> = 0) // return DP [left] [right] has been obtained from the left end to the right end of a certain interval. if (Left = right) // indicates a pile of stones in the interval {return DP [left] [right] = 0;} int min, mid; For (mid = left; mid <right; Mid ++) {If (DP [left] [right] <0) DP [left] [right] = inf; // core: dynamic transfer equation min = dp (left, mid) + dp (Mid + 1, right) + (sum [Mid]-sum [left-1]) + (sum [right]-S Um [Mid]); If (Min <DP [left] [right]) DP [left] [right] = min;} return DP [left] [right];} int main () {int N, I, A; while (~ Scanf ("% d", & N) {// n indicates the number of stones heap for (I = 1; I <= N; I ++) {scanf ("% d", & A); // A indicates the number of stones in heap I in sequence sum [I] = a + sum [I-1];} memset (DP, -1, sizeof (DP); printf ("% d \ n", dp (1, N);} return 0 ;}Interval DP problem!
# Include <stdio. h> # define INF 2000000005int DP [205] [203], sum [203]; int min (int A, int B) {return A> B? B: A;} int main () {int N, A; while (~ Scanf ("% d", & N) {for (INT I = 1; I <= N; I ++) {scanf ("% d", & ); sum [I] = sum [I-1] + A; DP [I] [I] = 0;} // interval dpfor (INT COUNT = 2; count <= N; count ++) {// traverse and merge COUNT = 2, 3 ,... N heap situation for (INT start = 1; Start <= N-count + 1; Start ++) {// start indicates the start point of each interval int end = start + count-1; // end indicates the end point of the interval DP [start] [end] = inf; for (INT mid = start; Mid <= end; Mid ++) {DP [start] [end] = min (DP [start] [end], DP [start] [Mid] + dp [Mid + 1] [end] + sum [end]-sum [start-1]) ;}} printf ("% d \ n", DP [1] [N]);} return 0 ;}