1021 Stone Merge Base time limit: 1 seconds space limit: 131072 KB score: 20 Difficulty: 3-level algorithm topic collection attention n heap of stones into a line. It is now necessary to merge the stones into a pile in order. It is stipulated that each of the next 2 stones can be merged into a new pile each time, and a new pile of stones is counted as the cost of the merger. Calculates the minimum cost of merging n heap stones into a heap. For example: 1 2 3 4, there are a number of merger methods 1 2 3 4 = 3 3 4 (3) + 6 4 (9) + (1) 2 3 4 1----5 4 5 (1) = 9 10 (+) + 24 (1) 2 3 4 = 1 2 7 (7) = 3 7 (Ten) + 10 (20) in parentheses for the total cost, it can be seen that the first method has the lowest cost and now gives the number of n heap stones, calculating the minimum combined cost. Input
Line 1th: N (2 <= n <= 100) Number of 2-n + 1:n heap stones (1 <= a[i] <= 10000)
Output
Minimum combined cost of output
Input example
41234
Output example
19
This problem is easy to look at the greedy direction, then read the hint to know is DP, but do not know how DP.
1#include <stdio.h>2#include <string.h>3#include <algorithm>4#include <iostream>5 using namespacestd;6 Const intINF =1<< -;7 intsum[1005];8 intvis[1005];9 intdp[1005][1005];Ten intMain () { One intN; A while(~SCANF ("%d",&N)) { - inti,len,temp; -memset (Vis,0,sizeof(Vis)); thememset (SUM,0,sizeof(sum)); -Memset (DP,0,sizeof(DP)); - for(i=1; i<=n;i++){ -scanf"%d",&vis[i]); +sum[i]=sum[i-1]+Vis[i]; - } + for(len=1; len<n;len++){ A for(i=1; i+len<=n;i++){ atDp[i][i + len] =INF; -temp=sum[i+len]-sum[i-1]; - for(intk=i;k<i+len;k++) -Dp[i][i+len]=min (dp[i][i+len],dp[i][k]+dp[k+1][i+len]+temp); - } - } inprintf"%d\n", dp[1][n]); - } to}
51nod 1021 Stone Merge