POJ 1738:An old Stone Game 石子归并 (GarsiaWachs算法)

Posted 午夜的行人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. 

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. 

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算法)的主要内容,如果未能解决你的问题,请参考以下文章

poj1738 An old Stone Game

POJ 1740:A New Stone Game

POJ 1740 A New Stone Game(博弈)

poj1740 A New Stone Game

POJ1385 Lifting the Stone 多边形重心

poj-2232 New Stone-Forfex-Cloth Game 思维题