hdu 4283 You Are the One

题目:

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
  
5
1
2
3
4
5

5
5
4
3
2
2

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

思路:

给定一群人,每个人有一个怒气值Di,这群人要上场,越晚上怒气值越高,第i个人如果是第k个出场,那么最后的怒气值总值增加Di * (k-1), 如果第i个人暂时不让他出场,可以把他放小黑屋,让其后面的人上场,求最小的总怒气值。

需要注意的是小黑屋(其实就是个堆栈),可以一定程度上调整上场程序。注意是一定程度上调整,把它当成堆栈想。这样贪心就不能了。应该是区间dp。

dp[i][j]表示第i个人到第j个人区间的最小总怒气值。
在i~j中选取i出场位置。
对于i,假设它的出场位置在第k个位置上,则前面有k-1个人,后面有j-k个人,那么划分成两个子区间dp[i+1][k],dp[k+1][j]。

dp[i][j] = min(dp[i][j],dp[i+1][k]+dp[k+1][j]+Di[i]*(k-i)+(sum[j]-sum[k])*(k-i+1));

代码:

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
int Di[105], dp[105][105], sum[105];
int main()
{
    int T,n;
    scanf("%d",&T);
    for (int t = 1; t <= T;t++){
        scanf("%d",&n);
        memset(sum,0,sizeof(sum));
        memset(dp,0,sizeof(dp));
        for (int i = 1; i <= n; i++){
            scanf("%d",&Di[i]);
            sum[i] = sum[i - 1] + Di[i];
        }
        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 + len <= n; i++){
                int j = i + len;  //i为区间起点,j为区间终点
                for (int k = i; k <= j; k++){
                    dp[i][j] = min(dp[i][j],dp[i+1][k]+dp[k+1][j]+Di[i]*(k-i)+(sum[j]-sum[k])*(k-i+1));
                }
            }
        }
        printf("Case #%d: %d\n",t,dp[1][n]);
    }
    return 0;

你可能感兴趣的:(动态规划,HDU,区间DP)