HDU - 4283 You Are the One 区间dp

The TV shows such as You Are the One has been very popular. In order to meet the need of boys who are still single, TJUT hold the show itself. The show is hold in the Small hall, so it attract a lot of boys and girls. Now there are n boys enrolling in. At the beginning, the n boys stand in a row and go to the stage one by one. However, the director suddenly knows that very boy has a value of diaosi D, if the boy is k-th one go to the stage, the unhappiness of him will be (k-1)*D, because he has to wait for (k-1) people. Luckily, there is a dark room in the Small hall, so the director can put the boy into the dark room temporarily and let the boys behind his go to stage before him. For the dark room is very narrow, the boy who first get into dark room has to leave last. The director wants to change the order of boys by the dark room, so the summary of unhappiness will be least. Can you help him? 

Input

  The first line contains a single integer T, the number of test cases.  For each case, the first line is n (0 < n <= 100) 
  The next n line are n integer D1-Dn means the value of diaosi of boys (0 <= Di <= 100) 

Output

  For each test case, output the least summary of unhappiness . 

Sample Input

2
  
5
1
2
3
4
5

5
5
4
3
2
2

Sample Output

Case #1: 20
Case #2: 24

题意:给你一个入栈的顺序,假设第x个元素是第y出栈,那么第x贡献的价值为(y-1)*a[x],让你求区间【1,n】的最小价值

思路:dp[i][j]表示区间[i,j]的元素全部出栈的最小价值,     注意假设i<=k&&k<=j 那么k的出栈顺序是1到j-i+1;

在区间【i,j】中那么 第i个元素可以第1个出栈,,,,第j-i+1个出栈,假设第k个出栈   区间【i+1,k】的出栈顺序仍然是  i到k-(i+1)+1;也就是说区间【i+1,k】贡献的价值是dp[i+1][k],   a[i]原来在区间【i,i]中第一个出栈,现在在区间【i,j】中第k个出栈那么a[i]贡献为 a[i]*(k-1),  区间【k+1,j】以前是第1到第j-(k+1)+1出栈,现在是  第k+1到j-(k+1)+1+k出栈贡献的价值为

(sum[j]-sum[i+k-1])*k+dp[i+k][j];

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<deque> 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<double,double>P;
const int len=1e2+5;
const double pi=acos(-1.0);
const ll mod=1e8+7;
int dp[len][len];
int a[len],sum[len]; 
int main()
{
	int Case=0;
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n; 
		for(int i=1;i<=n;++i)
		{
			scanf("%d",&a[i]);
			sum[i]=sum[i-1]+a[i];
		}
		memset(dp,0,sizeof(dp));
		for(int i=1;i<=n;++i)
			for(int j=i+1;j<=n;++j)dp[i][j]=0x3f3f3f3f;
		for(int le=2;le<=n;++le) 
		{
			for(int i=1;i+le-1<=n;++i)
			{
				int j=i+le-1;
				for(int k=1;k<=j-i+1;++k)
					dp[i][j]=min(dp[i][j],dp[i+1][i+k-1]+a[i]*(k-1)+dp[i+k][j]+(sum[j]-sum[k+i-1])*k);
			}
		}
		printf("Case #%d: %d\n",++Case,dp[1][n]);
	}
}


 

猜你喜欢

转载自blog.csdn.net/hutwuguangrong/article/details/88556590