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

题目连接:https://vjudge.net/contest/229444#problem/G

题意:有n个人,要一个一个的登台,每个人都有一个值,如果他是第k个登台的,他的最终的的值就等于他的diaosi值*(k-1), 他前边等待了K-1个人,现在要确定一个登台顺序 ,使得所有男孩的diaosi值最小。

原先以为是贪心做法,wa了一发。由于调整不能是随心所欲的调整,是跟栈有关的调整。因此是一个区间DP。

dp[i][j]表示从第i个人到第j个人这段区间的最小花费,对于dp[i][j]的第i个人, 可能上场的可能有j-i+1种。考虑第i人 是 第k个上场即在i之后的k-1个人是率先上场的,那么就出现了一个子问题 dp[i+1][i+k]表示在第i个人之前上场的, 对于第i个人,由于是第k个上场的,值是a[i]*(k-1)
其余的人是排在第k+1个之后出场的,也就是一个子问题dp[i+k][j],对于这个区间的人,由于排在第k+1个之后,所以整体值要加上k*sigma( a(i+k),a (j) )。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;

const int inf = 0x3f3f3f3f;
const int maxn = 105;
int dp[maxn][maxn];
int a[maxn], sum[maxn];
int n;

int main()
{
    int t;
    cin >> t;
    int cas = 0;
    while(t --)
    {
        memset(sum, 0, sizeof sum);
        memset(dp, 0, sizeof dp);
        cin >> n;
        for(int i = 1; i <= n; i++)
        {
            cin >> a[i];
            sum[i] = sum[i-1]+a[i];
        }
        for(int i = 1; i <= n; i++)
            for(int j = i+1; j <= n; j++)
                dp[i][j] = inf;
        for(int l = 1; l < n; l++)
            for(int i = 1; i+l <= n; i++)
            {
                int j = i+l;
            //    dp[i][j] = inf; 
                for(int k = i; k <= j; k++)
                    dp[i][j] = min(dp[i][j], a[i]*(k-i)+(k-i+1)*(sum[j]-sum[k])+dp[i+1][k]+dp[k+1][j]);
            }
        printf("Case #%d: %d\n",++cas, dp[1][n]);
    }
 } 
 
 /*
 2
 5 
 1 2 3 4 5
 5 
 5 4 3 2 2
 */

猜你喜欢

转载自blog.csdn.net/qq_38295645/article/details/81252885