1. 程式人生 > 實用技巧 >You Are the One solution

You Are the One solution

question:

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

solution:

1.在一個區間 [l, j] 內,如果l是第 k (1<=k<=j-l+1)個出場的,那麼 [l+1, l+k-1] 必定是先與l出場的,剩下的 [l+k, j] 是在l之後出場的。

2.如果確定了l在區間 [l, j] 是第k個出場的,可以把區間分為 [l+1, l+k-1] 和 [l+k, j],兩個區間互不影響,也可以分別對這兩個區間單獨求值。

其在當前區間內是第k個出場的,先得到 D[l]*(k-1)。對於區間[l+1, l+k-1]的人,是先於l出場的,對於總體,他們是沒有延遲的,直接加上dp[l+1, l+k-1]。對於區間[l+k, j]的人,他們是在l之後出場的,l在這個區間內又是第k個出場的,對於[l+k, j]這個總體,他們是整體延遲了k個人的,加上 k*(sum[j]-sum[l+k-1]),加上了延遲所帶來的值就可以把區間[l+k, j]的出場是沒有延遲的,情況跟區間[l+1, l+k-1]一樣,再加上dp[l+k, j]。

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1001
#define INF 0x3f3f3f3f
using namespace std;
int D[N];
int sum[N];
int dp[N][N];
int main()
{
    int T;
    scanf("%d",&T);
    int Case=1;
    while(T--)
    {
        int n;
        sum[0]=0;
        scanf("%d",&n);
        memset(dp,0,sizeof(dp));
        memset(sum,0,sizeof(sum));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&D[i]);
            sum[i]=sum[i-1]+D[i];
        }
        
        for(int len=1;len<n;len++)
        {
            for(int i=1;i<=n;i++)
            {
                int j=i+len;
                if(j<=i)
                dp[i][j]=0;
                else
                dp[i][j]=INF;
                for(int k=1;k<=j-i+1;k++)
                    
                    dp[i][j]=min(dp[i][j],dp[i+1][i+k-1]+dp[i+k][j]+(k-1)*D[i]+k*(sum[j]-sum[i+k-1]));
            }
        }
        printf("Case #%d: %d\n",Case++,dp[1][n]);  
    }
    return 0;
}