HDU3506 Monkey Party(区间DP)

HDU3506 Monkey Party(区间DP)

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

题意

区间dp模板题,用到了四边形不等式优化。题目中的数据是围成环形的,利用x[i+n]=x[i]以及前缀和数组来模拟环形。

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<vector>
#include<functional> 
#include<map>
using namespace std;
typedef long long ll;
const int N=1e5+10,NN=2e3+10,INF=0x3f3f3f3f;
const ll MOD=1e9+7;
int n;
int sum[N],x[N];
int dp[NN][NN],s[NN][NN];//dp数组表示从i到j的最小时间,s数组表示从i到j的最优分割点
void minval(){
	memset(dp,INF,sizeof dp);
	for(int i=1;i<=2*n;i++){
		sum[i]=sum[i-1]+x[i];//前缀和数组
		dp[i][i]=0;
		s[i][i]=i;//i到本身的最优分割点是其本身
	}
	for(int len=2;len<=n;len++){
		for(int i=1;i+len-1<2*n;i++){
			int j=i+len-1;
			for(int k=s[i][j-1];k<=s[i+1][j];k++){
				if(dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1]<dp[i][j]){
					dp[i][j]=dp[i][k]+dp[k+1][j]+sum[j]-sum[i-1];
					s[i][j]=k;
				}
			}
		}
	}
	int minn=INF;
	for(int i=1;i<=n;i++) minn=min(minn,dp[i][i+n-1]);
	printf("%d\n",minn);
}
void init(){
	sum[0]=0;
}
int main(){
	while(~scanf("%d",&n)){
		init();
		for(int i=1;i<=n;i++){
			scanf("%d",&x[i]);
			x[i+n]=x[i];//模拟环形
		}
		minval();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Hc_Soap/article/details/107402900