Monkey Party(即合并石子(环形))

这是一篇关于 Monkey Party,即环形合并石子问题的解析文章。文章介绍了问题背景,规则,以及如何求解的详细过程。通过示例输入和输出解释了问题,并给出了多版代码实现,包括暴力搜索、状态转移方程优化和更进一步的优化策略,旨在找到合并石子的最小时间。
摘要由CSDN通过智能技术生成

目录

目录

题目(环形合并石子)

Input

Output

Sample Input

Sample Output

解析

代码 1.0

代码 2.0

正解

代码 3.0

再优化

代码 4.0


题目(环形合并石子)

 

Far away from our world, there is a banana forest. And many lovely monkeys live there. One day, SDH(Song Da Hou), who is the king of banana forest, decides to hold a big party to celebrate Crazy Bananas Day. But the little monkeys don't know each other, so as the king, SDH must do something. 
Now there are n monkeys sitting in a circle, and each monkey has a making friends time. Also, each monkey has two neighbor. SDH wants to introduce them to each other, and the rules are: 
1.every time, he can only introduce one monkey and one of this monkey's neighbor. 
2.if he introduce A and B, then every monkey A already knows will know every monkey B already knows, and the total time for this introducing is the sum of the making friends time of all the monkeys A and B already knows; 
3.each little monkey knows himself; 
In order to begin the party and eat bananas as soon as possible, SDH want to know the mininal time he needs on introducing. 

(题目解析见百度翻译)

Input

There is several test cases. In each case, the first line is n(1 ≤ n ≤ 1000), which is the number of monkeys. The next line contains n positive integers(less than 1000), means the making friends time(in order, the first one and the last one are neighbors). The input is end of file.

Output

For each case, you should print a line giving the mininal time SDH needs on introducing.

Sample Input

8
5 2 4 7 6 1 3 9

Sample Output

105

解析

首先,很容易想到状态转移方程:

\large f[i][j] = f[i][k] + f[k + 1][j] + w[i][j] \rightarrow i != j

\large f[i][j] = 0 \rightarrow i == j

这里提一下  f[i][j] 表示 把 第  第 j 堆全部合并在在一起的最小代价。

然而他又是个环形,所以我们只好将前面 n - 1 段复制到 第 n 段后面,这样处理

for (reg int i = 1;i <= n; ++ i){
    scanf("%d",&a[i]);       
    w[i] = w[i - 1] + a[i];
}
for (reg int i = 1;i <= n; ++ i)
     w[i + n] = w[i + n - 1] + a[i];

这里复制的是 w 的值,通过状态转移方程可知,它们跟 a 没有任何关系

然后我们可以通过 平行四边形的不等式优化 进行分析(这里有讲解

首先为了便于理解,我们看一份代码,消化一下前面的知识

代码 1.0

#include<cstdio>
#include<cstring>
#define M 2000 + 5
#define reg register
#define INF 0x7f7f7f7f

int a[M],w[M],f[M][M];
int n;

int main(){
    while(scanf("%d",&n) == 1){
        memset(f,127,sizeof(f));
        for (reg int i = 1;i <= n; ++ i){
            scanf("%d",&a[i]);
            w[i] = w[i - 1] + a[i];//前缀和,求 1 到 i 的费用
            f[i][i] = 0;//清 0 
        }
        for (reg int i = 1;i <= n; ++ i){//同上
            w[i + n] = w[i + n - 1] +
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值