Monkey Party - HDU 3506 四边形不等式优化

来源:互联网 发布:美丽折淘宝客助手 编辑:程序博客网 时间:2024/05/22 02:08

Monkey Party

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 979    Accepted Submission(s): 432


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
85 2 4 7 6 1 3 9
 

Sample Output
105
 


题意:n个猴子围成一圈,每次猴子都有一个权值,两个相邻的猴子称为朋友的话,他们的朋友也会称为朋友,所需的时间是这些猴子的权值的和。求让所有猴子称为朋友所需时间的最小值。

思路:首先将环形化成线性的来做,dp[i][j]表示从i到j的猴子都是朋友的最小所需时间。

dp[i][j]=min(dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1])。

用四边形不等式来优化。

AC代码如下:

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;typedef long long ll;int T,t,n,m;int dp[2010][2010],s[2010][2010],sum[2010],num[2010],INF=1e9;int main(){    int i,j,k,ret,ans,len;    while(~scanf("%d",&n))    {        for(i=1;i<=n;i++)        {            scanf("%d",&num[i]);            num[i+n]=num[i];        }        for(i=1;i<=n*2;i++)           sum[i]=sum[i-1]+num[i];        for(i=1;i<=n*2;i++)           s[i][i]=i-1;        for(len=1;len<=n;len++)           for(i=1;i+len<=n*2;i++)           {                j=i+len;                dp[i][j]=INF;                for(k=s[i][j-1];k<=s[i+1][j];k++)                {                    ret=dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1];                    if(ret<dp[i][j])                    {                        dp[i][j]=ret;                        s[i][j]=k;                    }                }            }        ans=INF;        for(i=1;i<=n;i++)           ans=min(ans,dp[i][i+n-1]);        printf("%d\n",ans);    }}



0 0
原创粉丝点击