描述
有N堆石子排成一排,每堆石子有一定的数量。现要将N堆石子并成为一堆。合并的过程只能每次将相邻的两堆石子堆成一堆,每次合并花费的代价为这两堆石子的和,经过N-1次合并后成为一堆。求出总的代价最小值。
-
输入
-
有多组测试数据,输入到文件结束。
每组测试数据第一行有一个整数n,表示有n堆石子。
接下来的一行有n(0< n <200)个数,分别表示这n堆石子的数目,用空格隔开
输出
- 输出总代价的最小值,占单独的一行 样例输入
-
3 1 2 3 7 13 7 8 16 21 4 18
样例输出
-
9
239
-
-
-
#include<iostream> #include<cstdio> using namespace std; const int N=210; int n,t,stone[N],ans; void combine(int k){ int tmp=stone[k]+stone[k-1]; ans+=tmp; for(int i=k;i<t-1;i++) stone[i]=stone[i+1]; t--; int j; for(j=k-1;j>0 && stone[j-1]<tmp;j--) stone[j]=stone[j-1]; stone[j]=tmp; while(j>=2 && stone[j]>=stone[j-2]){ int d=t-j; combine(j-1); j=t-d; } } int main(){ while(scanf("%d",&n)!=EOF){ for(int i=0;i<n;i++) scanf("%d",&stone[i]); t=1,ans=0; for(int i=1;i<n;i++){ stone[t++]=stone[i]; while(t>=3 && stone[t-3]<=stone[t-1]) combine(t-2); } while(t>1) combine(t-1); printf("%d\n",ans); } return 0; }