Problem Description
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
题意
相当于一堆石子排成一个环,每次操作可以将两堆石子合并为一堆,分数为两堆石子之和,问最小值
思路
环的问题,可以转化为两个相同的行拼成一块。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int x,n,a[2010],dp[2010][2010],s[2010][2010];
int sum[2010];
int main()
{
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++) {scanf("%d",&a[i]); }
for(int i=n+1;i<=2*n;i++) {a[i] = a[i-n];}
for(int i=1;i<=2*n;i++){
sum[i] = sum[i-1] + a[i];
dp[i][i] = 0;
s[i][i] = i;
}
for(int l=2;l<=2*n;l++){
for(int i=1;i<=2*n;i++){
int j = i+l-1;
if(j>2*n) continue;
int mmin = inf;
for(int k=s[i][j-1];k<=s[i+1][j];k++){
int t = dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1];
if(t<mmin){
mmin = t;
s[i][j] = k;
}
}
dp[i][j] = mmin;//printf("i:%d j:%d dp:%d\n",i,j,mmin);
}
}
int mmin = inf;
for(int i=1;i<=n;i++){
if(mmin>dp[i][i+n-1]) mmin = dp[i][i+n-1];
}
printf("%d\n",mmin);
}
return 0;
}