首页 > 代码库 > POJ 1738:An old Stone Game 石子归并 (GarsiaWachs算法)
POJ 1738:An old Stone Game 石子归并 (GarsiaWachs算法)
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
1 #include <stdio.h> 2 #include <iostream> 3 #include <cstring> 4 #include <algorithm> 5 #define MAX 55555 6 using namespace std; 7 int a[MAX],n,num,result; 8 void combine(int k) 9 { 10 int i,j; 11 int temp=a[k]+a[k-1]; 12 result+=temp; 13 for(i=k;i<num-1;i++) 14 a[i]=a[i+1]; 15 num--; 16 for(j=k-1;j>0&&a[j-1]<temp;j--) 17 a[j]=a[j-1]; 18 a[j]=temp; 19 while(j>=2&&a[j]>=a[j-2]) 20 { 21 int d=num-j; 22 combine(j-1); 23 j=num-d; 24 } 25 } 26 int main() 27 { 28 int i; 29 while(scanf("%d",&n)&&n){ 30 if(n==0) return 0; 31 for(i=0;i<n;i++) 32 scanf("%d",&a[i]); 33 num=1; 34 result=0; 35 for(i=1;i<n;i++){ 36 a[num++]=a[i]; 37 while(num>=3&&a[num-3]<=a[num-1]) 38 combine(num-2); 39 } 40 while(num>1) combine(num-1); 41 printf("%d\n",result); 42 } 43 return 0; 44 }
POJ 1738:An old Stone Game 石子归并 (GarsiaWachs算法)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。