You Are the One_dp

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个人排成队,每个人有一个值a[i],不开心指数是第k个就用(k-1)*a[i],可以用堆栈适当调整位置,求最小的不开心指数之和。

【思路】用dp[i][j]表示i到j这段最小的不开心指数。第i既可能是第一个也可能是j-i+1个。

i和j之间存在k,即i+1后的k-1个人在第i个人之前,则dp[i+1][i+1+k-1-1]表示在第i个人之前的人的不开心指数,

对于第i个人排在第k个,则他的不开心指数a[i]*(k-1);剩下的人在k+1后,dp[i+k][j];排在k个后,不开心指数要加上

k*(sum[j]-sum[i+k-1])
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

const int inf=10000000;
const int N=107;
int a[N],sum[N];
int dp[N][N];
int main()
{
    int t,n,cas=1;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(sum,0,sizeof(sum));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            sum[i]=sum[i-1]+a[i];
            
        }
        memset(dp,0,sizeof(dp));
        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<=n-1;i++)
            {
                int j=i+l;
                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*(sum[j]-sum[i+k-1])+a[i]*(k-1));
                }
            }
        }
        printf("Case #%d: %d
",cas++,dp[1][n]);
        
    }
    return 0;
}
原文地址:https://www.cnblogs.com/iwantstrong/p/6367420.html