线性石子归并JOJ2521: Monkey and fruits

2521: Monkey and fruits


StatusIn/OutTIME LimitMEMORY LimitSubmit TimesSolved UsersJUDGE TYPE
stdin/stdout3s8192K31250Standard
After culling his most favorite fruits from the trees in an orchard,Keen AS, a mischievous monkey, is confused of the way in which he can combine these piles of fruits into one in the most laborsaving manner. Each turn he can merely combine any two piles into a larger one. Obviously, by combining N-1 times for N piles of fruits, one pile results eventually. It always takes AS a certain quantity of units of stamina, which equals to the sum of the amounts of fruits in each of the two piles combined, to complete a combination. For instance, given three piles of fruits, containing 1, 2, and 9 fruits respectively, the combination of 1 and 2 would cost 3=1+2 units of stamina, and two piles-3 and 9-are resulted; finally, combining them would cost another 12=3+9 units of stamina, and the total units of stamina taken in the whole procedure is 15=3+12. Surely there are many a possible means to combine these three piles; however, it can be proved that 15 is the minimum amount of units of stamina in demand, and that is what your program is required to do. in this problem ,the fruits are put in a strait line. A pile of fruits 'P' can only combined with the rightest pail on the left of P or the leftest on the right of P, and the united pile will at the position of the bigger one.

Input

The input file consists of many test cases. The first line contains an integer N (<=100), indicating the number of piles, and the second line contains N integers, each of which represents the amount of fruits in a pile. no integer will more than 10000, the sequence of integer also means the location of the piles.

Output

Your program should print the minimum amount of units of stamina that are required to combine these piles of fruits into one on request.

Sample Input

3
1 2 9

Sample Output

15
#include<iostream>  //求最小值 
int main()
{
 int n,i,j,k,r,t;
 int s[101][101],sum[101],a[101];
 while(scanf("%d",&n)!=EOF)
 {
   memset(s,0,sizeof(s));//初始化
   sum[0]=0;
      for(i=1;i<=n;i++) 
   {
   scanf("%d",&a[i]);
   sum[i]=sum[i-1]+a[i];
   }
   for(r=1;r<=n-1;r++) //这个R指的是头尾间距
     for(i=1;i<=n-r;i++)
  {
   j=i+r;
   s[i][j]=s[i][i]+s[i+1][j]+sum[j]-sum[i-1];//注意是I-1 ,并且s[i][i]+s[i+1][j],S[I][I]是有值的!
   for(k=i+1;k<j;k++)
   {
    t=s[i][k]+s[k+1][j]+sum[j]-sum[i-1];
    if(t<s[i][j]) s[i][j]=t;
   }
  }
  printf("%d/n",s[1][n]);
 }    
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值