The problem is described in a straight line there are n heap of stones, each heap has a certain number, each can be two piles of adjacent stones merged, merged and placed in two piles in the middle position, the combined cost of the sum of two piles of stones. To combine all the stones into a pile of minimum costs. Input format input The first line contains an integer n, which represents the number of heaps of pebbles.
The next line, containing n integers, gives the size of each heap in order. The output format outputs an integer that represents the minimum cost of the merge. Sample Input 5
1 2 3 4 5 sample output 33 data size and convention 1<=n<=1000, at least 1 stones per heap, up to 10000 capsules.
Exercises
#include <stdio.h>#include<stdlib.h>#defineInif 0x3f3f3f3fintN;intdp[1001][1001] = {0};intsum[1001][1001];intnum[1001];voidMinsz () {intI, J, K, T, Len, Minx; for(i =1; I <= N; i++) {Sum[i][i]=Num[i]; for(j = i +1; J <= N; J + +) {Sum[i][j]= sum[i][j-1] + num[j];//calculate the distance from a heap to a heap } } for(j =2; J <= N; J + +) { for(i = j-1; i >0; i--) {Minx=inif; DP[I][J]=inif; for(k = i; k < J; k++) {T= Dp[i][k] + dp[k+1][J] +Sum[i][j]; if(T <Minx) Minx=T; } Dp[i][j]=Minx; }} printf ("%d\n", dp[1][n]);}intMain () {inti; scanf ("%d", &N); for(i =1; I <= N; i++) {scanf ("%d", &Num[i]); } Minsz (); return 0;}
View Code
Algorithm to improve the combined stone (DP)