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
GarsiaWachs算法是从第一个石堆开始找符合stone[k-1]<stone[k+1]的石堆k,然后合并k-1与k堆,再向前找j堆石子,满足stone[j]>stone[k]+stone[k-1],插入到石堆j的后面。然后重新寻找。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int a[50010];
int now,ans;
int n;
void sol(int x)
{
int i,j,tmp;
tmp = a[x-1] + a[x];
ans += tmp;
for(i=x; i<now-1; i++)
a[i] = a[i+1];
now--;
for(j=x-1; j>0&&a[j-1]<tmp; j--)
a[j] = a[j-1];
a[j] = tmp;
while(j>=2 && a[j] >= a[j-2])
{
int dis = now - j;
sol(j-1);
j = now - dis;
}
return ;
}
int main()
{
while(~scanf("%d", &n))
{
if(n==0)break;
for(int i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
now = 1;
ans = 0;
for(int i=1; i<n; i++)
{
a[now++] = a[i];
while(now >= 3 && a[now-3] <= a[now-1])
{
sol(now-2);
}
}
while(now > 1) sol(now-1);
cout << ans << endl;
}
return 0;
}
水波.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)