WOJ1299-Merge Apple

来源:互联网 发布:淘宝店怎么打造爆款 编辑:程序博客网 时间:2024/06/17 09:50

In front of Sandy lays a big table, on which there're piles of apples formed a line. That looks good, but his mother doesn't like it, so Sandy has to put them together. Since Sandy's always weak and thin, he wants to calculate the minimum energy it may cost. 
Considering two piles of apples consisting of a and b apples respectively, if Sandy wants to merge them, he must spend a+b shares of energy. In order to save his energy to the max, he will merge two neighbouring piles each time, and repeat the process until all apples are in one pile.

输入格式

There're mutiple test cases.
The first line contains an integer N(2<=N<=100), indicating the number of piles on the table.
N numbers between 1 and 100 following in the second line indicate the numbers of apples in N piles, respectively.
Input ends up with a single 0 which shouldn't be processed.

输出格式

For each case output a line containing an integer, poingting out the minimum energy Sandy has to spend.

样例输入

4 4 4 5 90

样例输出

43


#include<stdio.h>#include<string.h>int n,i,j,k,x,v[101],dp[101][101];int min(int a,int b){    return a>b?b:a;}int main(){    while((scanf("%d",&n)!=EOF)&&n!=0){v[0]=0;for (i=1;i<=n;i++){        scanf("%d",&x);        v[i]=v[i-1]+x;    }    memset(dp,10000,sizeof(dp));for(i=1;i<=n;i++) dp[i][i]=0;for(i=n-1;i>=1;i--)        for(j=i+1;j<=n;j++)            for(k=i;k<=j-1;k++)                dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+v[j]-v[i-1]);    printf("%d\n",dp[1][n]);}    return 0;}


原创粉丝点击