Stone merger (1)
Time Limit:
1000
ms | Memory Limit:
65535
KB
Difficulty:
3
- describe
- There are N piles of stones arranged in a row, and each pile has a certain number of stones. Now take N piles of stones and make them into one pile. In the process of merging, only two adjacent piles of stones can be piled into one pile at a time. The cost of each merger is the sum of the two piles of stones, and it becomes a pile after N-1 mergers. Find the total cost minimum.
- enter
-
There are multiple sets of test data, input to the end of the file.
The first line of each set of test data has an integer n, which means there are n piles of stones.
The next line has n (0<n<200) numbers, which represent the number of n piles of stones, separated by spaces - output
- Output the minimum value of the total cost, on a separate line
- sample input
-
3 1 2 3 7 13 7 8 16 21 4 18
- Sample output
-
9 239
#include<stdio.h> #include<algorithm> using namespace std; int dp[200][200],a[200],inf=1e9,sum[200]; intmain() { int n; while(~scanf("%d",&n)) { int i,j,k; for(i=1; i<=n; i++) scanf("%d",&a[i]),sum[i]=a[i]+sum[i-1]; //sum[i] is the sum of the previous i items for(i=1; i<=n; i++) for(j=i; j<=n; j++) dp[i][j]=i==j?0:inf;//求最小代价,初始化正无穷 for(i=1; i<n; i++) //i表示区间间隔为i for(j=1; j<=n-i; j++)//j表示区间左端点 for(k=j; k<=i+j-1; k++)//k表示[i,i+j)区间中间的点 dp[j][i+j]=min(dp[j][i+j],dp[j][k]+dp[k+1][i+j]+sum[i+j]-sum[j-1]); //sum[i+j]-sum[j-1]为第j项到第i+j项的总和。 printf("%d\n",dp[1][n]); } return 0; }