HDU4283-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,如果他是第k个上台表演,他的不开心值为:x(k-1),在舞台旁边有一个小巷子,巷子很长而且很窄,不能让两个人并排通过,导演可以通过这个巷子调整这列人的上台顺序。每个人只能按照排列好的顺序进入巷子!

分析:
题意很清楚,就是用一个栈来调整这列人上台的顺序!但是很难下手啊!虽然用暴力搜索可能可以解决,但是这个专题是DP啊!难搞了!

看大佬们的题解,很牛的思路,还是太菜了啊!

我们永远以第一个人为标尺,如果他是第k个上台表演的,那么2~k的人肯定比他先上台,k+1 ~ n的人肯定比第一个人上台上得晚,那么我们就很容易将大规模的数据减小了!这就符合DP的基本思想了!

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 105
#define INF 0x3f3f3f3f

using namespace std;

int  book[N];
int dp[N][N];
int sum[N];

int main()
{
	int n,T;
	scanf("%d",&T);
	for(int t=1;t<=T;t++)
	{
		sum[0]=0;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&book[i]);
			sum[i]=sum[i-1]+book[i];
		}
		memset(dp,0,sizeof(dp));
		for(int i=1;i<=n;i++)
		{
			for(int j=i+1;j<=n;j++)
			{
				dp[i][j]=INF;
			}
		}
		for(int len=1;len<n;len++)
		{
			for(int i=1;i<=n-len;i++)
			{
				int j=i+len;
				for(int k=i;k<=j;k++)
				{
					dp[i][j]=min(dp[i][j],(k-i)*book[i]+(k-i+1)*(sum[j]-sum[k])+dp[i+1][k]+dp[k+1][j]);
				}
			}
		}
		printf("Case #%d: %d\n",t,dp[1][n]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43357583/article/details/105757229