目录
目录
题目(环形合并石子)
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
解析
首先,很容易想到状态转移方程:
这里提一下 f[i][j] 表示 把 第 i 堆 到 第 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] +