hdu4283(區間DP)

地址:http://acm.hdu.edu.cn/showproblem.php?pid=4283

You Are the One

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


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

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

題意:有n個人參加電視節目,每個人都有一個憤怒值Di,若這個人是第k位上場的選手的話,他所產生的憤怒值是(k-1)*Di。在才賽通道旁邊有個小黑屋可以作爲棧來使隊伍序列改變,問最小產生的憤怒值是多少。

思路:一開始認爲是記憶化搜索,但是超時了。百度了下發現是區間DP,瞭解了下區間DP的定義然後自己編了下代碼試試,立馬就出錯了,我在編寫代碼時區間內保存的是最優值,沒有考慮對於別的情況是否適用,所以WA。

           區間DP就是在區間內求得最優解,然後再組合在一起得出最優解。

           對於該題來說,建立數組dp[i][j]表示從i號選手到j號選手上臺所產生的最小憤怒值。

           dp[i][j]中i可以第一個上臺,也可以第j-i+1個上臺,所以我們要遍歷i的位置來求最小的憤怒值。

代碼:

#include<iostream>
#include<queue>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL __int64
#define Mod 0xfffffff
int dp[110][110],num[110],sum[110]={0};
int main(){
    int t,cas=1,n;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            scanf("%d",&num[i]);
            sum[i]=sum[i-1]+num[i];
        }
        for(int l=1;l<n;l++){  //先將長度爲2的區間最優解全部求出,然後依次增加
            for(int i=1;i<=n-l;i++){
                int j=i+l;
                dp[i][j]=Mod;
                for(int k=1;k<=j-i+1;k++){  //表示i是第k個上臺的
                    dp[i][j]=min(dp[i][j],num[i]*(k-1)+dp[i+1][i+k-1]+dp[i+k][j]+(sum[j]-sum[i+k-1])*k);
                }
            }
        }
        printf("Case #%d: %d\n",cas++,dp[1][n]);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章