hdu 4283(区间dp)

来源:互联网 发布:叶蓓 知乎 编辑:程序博客网 时间:2024/04/29 16:26

Problem Description
  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  512345554322
 

Sample Output
Case #1: 20Case #2: 24


这题最重要的是要有思路,区间的相互关系;最重要的是要把思路写出来啊!!(百度好多大牛都直接贴代码不说清晰思路的,搞得我们这些新手情何以堪哭

我来说说自己的感悟吧,首先我觉得dp用记忆化搜索写起来是既简单又容易懂又好看的一种高效方法。

这题用dp[i][j]来表示第i个人到第j个人的最少不开心值,接下来,取i作为研究对象,他是i到j中第几个出场的呢?我们设为k,那么第一个出场的人我们应该要能推出来是第i+k-1个人,那么此时我们即将问题转化为了原问题与dp[i+1][i+k-1]+dp[i+k][j]之间的关系,他们之间有什么关系呢?首先一个是i已经单独提出来了,那么他自己的不开心值就为(k-1)*a[i],关注他之后再将焦点对准其他人,其他人的不开心值又有什么变化?第i个人之后的所有人的不开心值是不是因为第i个人而有影响?开一个数组sum[]记录总不开心值,那么多出来的不开心值就为k*(sum[j]-sum[i+k-1]);至此,我们分析完了所有人,便可得出答案:dp(i,j)=min{dp(i+1,i+k-1)+a[i]*(k-1)+dp(i+k,j)+(sum[j]-sum[i+k-1])*k}

接下来还等啥,赶紧敲代码呀!!!


#include<iostream>#include<algorithm>#include <cstdio>#include <cmath>#include<cstring>#define inf 1e8using namespace std;int a[105],sum[105],dp[105][105];int solve(int i,int j){    if(dp[i][j]!=-1)return dp[i][j];    if(i>=j)return dp[i][j]=0;    dp[i][j]=inf;    for(int k=1;k<=j-i+1;k++)        dp[i][j]=min(solve(i+1,i+k-1)+solve(i+k,j)+(k-1)*a[i]+k*(sum[j]-sum[i+k-1]),dp[i][j]);    return dp[i][j];}int main (){    int t;cin>>t;int o=1;    while(t--)    {        int n;cin>>n;        memset(a,0,sizeof(a));        memset(dp,-1,sizeof(dp));        for(int i=1;i<=n;i++)        {            cin>>a[i];            sum[i]=sum[i-1]+a[i];        }        printf("Case #%d: %d\n",o++,solve(1,n));    }    return 0;}



1 0
原创粉丝点击