Merge 1048 stones and 1048 stones
1048 merge stones
Time Limit: 1 s space limit: 128000 KB title level: Gold Title Description
Description
There are n piles of stones in a column, each pile of stones has a weight w [I], each merge can combine adjacent two piles of stones, the cost of one merge is the weight of two piles of stones and w [I] + w [I + 1]. Ask how to arrange the merge sequence to minimize the total merge cost.
Input description
Input Description
The first line is an integer n (n <= 100)
N integers w1, w2. .. wn (wi <= 100) in the second row)
Output description
Output Description
An integer indicates the minimum merge cost.
Sample Input
Sample Input
4
4 1 1 4
Sample output
Sample Output
18
Data range and prompt
Data Size & HintCATEGORY tag
Tags click here to expand
Pay attention to the values of I, j, and k in the array!
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<cstring> 5 using namespace std; 6 const int MAXN=101; 7 int a[MAXN]; 8 int f[MAXN][MAXN]; 9 int main()10 {11 memset(f,0x3f,sizeof(f));12 int n;13 scanf("%d",&n);14 for(int i=1;i<=n;i++)15 f[i][i]=0;16 for(int i=1;i<=n;i++)cin>>a[i];17 for(int i=2;i<=n;i++)a[i]=a[i]+a[i-1];18 for(int i=n;i>=1;i--)19 for(int j=i+1;j<=n;j++)20 for(int k=i;k<j;k++)21 f[i][j]=min(f[i][j],f[i][k]+f[k+1][j]+a[j]-a[i-1]);22 printf("%d",f[1][n]);23 return 0;24 }