-
题目
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
-
题意
与石子合并类似。
题意: 一群猴子围成一圈,每个猴子有一个权值,然后每次选相邻的两个猴子交友,代价就是两个权值和,a和b交友之后呢,a的朋友和b的朋友就是朋友了,代价是a,b的朋友的总和,让你求最小代价。
直接套区间DP的板子,会TLE,.
需要一个四边形不等式进行优化。Huffman编码-石子问题+平行四边形优化
反正我真的没太看懂。总之,就是一个式子https://www.luogu.org/blog/Hurricane-zjz/solution-p1880
dp[i][j]=min(dp[i][k]+dp[k+1][j])+sum[i][j] (p[i][j-1]<=k<=p[i+1][j])
初始化时,p[i][i]=i;
更新时,p[i][j]记录的是下标为i,j时的最优的k。
-
代码
//HDU 3506
#include<iostream>
#include<algorithm>
#include<set>
#include<cstring>
#include<queue>
#include<stack>
#include<vector>
#include<stdio.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn=2000+10;
int n;
int num[maxn];
int w[maxn];
ll dp[maxn][maxn];
int s[maxn][maxn];
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(dp,0,sizeof(dp));
// memset(w,0,sizeof(w));
// memset(num,0,sizeof(num));
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
num[i+n]=num[i];
}
for(int i=1;i<=2*n;i++)
w[i]=w[i-1]+num[i];
for(int i=1;i<=2*n;i++)
s[i][i]=i;
for(int len=2;len<=n;len++)
{
for(int l=1;l+len-1<=2*n;l++)
{
int r=len+l-1;
dp[l][r]=inf;
for(int k=s[l][r-1];k<=s[l+1][r];k++)
{
ll temp=dp[l][k]+dp[k+1][r]+w[r]-w[l-1];
if(dp[l][r]>temp)
{
dp[l][r]=temp;
s[l][r]=k;
}
}
}
}
ll ans=inf;
for(int i=1;i<=n;i++)
ans=min(ans,dp[i][i+n-1]);
printf("%lld\n",ans);
}
}