An old Stone Game
Time Limit: 5000MS | Memory Limit: 30000K | |
Total Submissions: 3691 | Accepted: 1042 |
http://poj.org/problem?id=1738
Description
There is an old stone game.At the beginning of the game the player picks n(1<=n<=50000) piles of stones in a line. The goal is to merge the stones in one pile observing the following rules:
At each step of the game,the player can merge two adjoining piles to a new pile.The score is the number of stones in the new pile.
You are to write a program to determine the minimum of the total score.
At each step of the game,the player can merge two adjoining piles to a new pile.The score is the number of stones in the new pile.
You are to write a program to determine the minimum of the total score.
Input
The input contains several test cases. The first line of each test case contains an integer n, denoting the number of piles. The following n integers describe the number of stones in each pile at the beginning of the game.
The last test case is followed by one zero.
The last test case is followed by one zero.
Output
For each test case output the answer on a single line.You may assume the answer will not exceed 1000000000.
Sample Input
1 100 3 3 4 3 4 1 1 1 1 0
Sample Output
0 17 8对于这个问题,用GarsiaWachs算法应该是最简单的,时间复杂度也可以达到O(nlogn)。
它的步骤如下:
设序列是stone[],从左往右,找一个满足stone[k-1] <= stone[k+1]的k,找到后合并stone[k]和stone[k-1],再从当前位置开始向左找最大的j,使其满足stone[j] > stone[k]+stone[k-1],插到j的后面就行。一直重复,直到只剩下一堆石子就可以了。在这个过程中,可以假设stone[-1]和stone[n]是正无穷的。
举个例子:
186 64 35 32 103
因为35<103,所以最小的k是3,我们先把35和32删除,得到他们的和67,并向前寻找一个第一个超过67的数,把67插入到他后面,得到:186 67 64 103,现在由5个数变为4个数了,继续:186 131 103,现在k=2(别忘了,设A[-1]和A[n]等于正无穷大)234 186,最后得到420。最后的答案呢?就是各次合并的重量之和,即420+234+131+67=852。
基本思想是通过树的最优性得到一个节点间深度的约束,之后证明操作一次之后的解可以和原来的解一一对应,并保证节点移动之后他所在的深度不会改变。具体实现这个算法需要一点技巧,精髓在于不停快速寻找最小的k,即维护一个“2-递减序列”朴素的实现的时间复杂度是O(n*n),但可以用一个平衡树来优化,使得最终复杂度为O(nlogn)。
上面是借了别人的,以后自己复习的时候也可以更快的理解。
1 #include<iostream> 2 #include<stdio.h> 3 #define maxx 50000 4 using namespace std; 5 6 int stone[maxx],n,t; 7 int ret; 8 9 void combine(int k) 10 { 11 int tmp=stone[k]+stone[k-1]; 12 ret+=tmp; 13 for(int i=k;i<t-1;i++)//两个合并了,就将后面的数据往前移一位 14 stone[i]=stone[i+1]; 15 t--; 16 int j; 17 for(j=k-1;j>0 && stone[j-1]<tmp;j--)//向前找到第一个比它大的数,并且放在它的后面 18 stone[j]=stone[j-1]; 19 stone[j]=tmp; 20 while(j>=2 && stone[j]>=stone[j-2]){ 21 int d=t-j; 22 combine(j-1); 23 j=t-d; 24 } 25 } 26 int main() 27 { 28 while(scanf("%d",&n),n){ 29 for(int i=0;i<n;i++) 30 scanf("%d",&stone[i]); 31 t=1,ret=0; 32 for(int i=1;i<n;i++){ 33 stone[t++]=stone[i]; 34 while(t>=3 && stone[t-3]<=stone[t-1])//保证至少有三个数才可以用这种算法,否则直接加就可以了。 35 combine(t-2); 36 } 37 38 while(t>1) combine(t-1); 39 printf("%d\n",ret); 40 } 41 return 0; 42 }
来源:http://www.cnblogs.com/zllwxm123/p/7246717.html