You Are the One
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6247 Accepted Submission(s): 3060
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
Source
题意
一些男孩上台表演,表演前要先进小黑屋准备,准备完后上台,并且只能最后一个进小黑屋的人才能上台表演,相当于一个栈,每一个男孩都有一个愤怒值a[i],i个男孩是第k个人上台,那么该男孩的愤怒总量就是(k - 1) * a[i],求所有男孩愤怒总量的最小值
思路
给出的顺序就是入栈的顺序,通过调整出栈顺序获得最小值;
区间dp: dp[i][j]表示 i 到 j 区间愤怒总量的最小值,不考虑 i 前面有人;
状态转移方程: dp[i][j] = min(dp[i][j], dp[i + 1][i + k - 1] + dp[i + k][j] + ((sum[j] - sum[i + k - 1]) * k)+ a[i] * (k - 1));
ps:(sum为前缀和数组)
k表示i ~ j 区间第 i 个人(即 i 到 j 区间第一个人)第 k 个上台表演,而 i + 1 到 i + k - 1 区间的人是在 a[i] 前面上台的,就划分出了一个子问题 dp[i + 1][i + k - 1],因为i + 1 到 i + k - 1 区间的人是先上台的,dp[i + 1][i + k - 1] 就是他们的愤怒总量;而 i + k 到 j 区间的人就是在 a[i] 最后上台的,有划分出了一个子问题,dp[i + k][j],但是由于该区间是在第 k 个后上台的,所以要加上他们的愤怒总量乘 k ,即 ((sum[j] - sum[i + k - 1]) * k);最后加上第 i 个人第 k 次上场的愤怒总量a[i] * (k -1),就是状态转移方程。
代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int dp[105][105], a[105], sum[105];
int main() {
int t;
while(cin >> t) {
int z = 0;
while(t--) {
memset(dp, inf, sizeof(dp));
int n;
cin >> n;
int c = 0;
for(int i = 1; i <= n; i++) {
cin >> a[i];
c += a[i];
sum[i] = c;
dp[i][i] = 0;
}
for(int len = 1; len <= n; len++) {
for(int i = 1; i + len - 1 <= n; i++) {
int end = i + len - 1;
for(int k = 1; k <= end - i + 1; k++) {
if(k == 1) {
dp[i][end] = min(dp[i][end], a[i]*(k-1) + dp[i+k][end] + (sum[end] - sum[i+k-1])*k);
} else if(k == end - i + 1) {
dp[i][end] = min(dp[i][end], dp[i+1][i+k-1] + a[i]*(k-1));
} else
dp[i][end] = min(dp[i][end], dp[i+1][i+k-1] + a[i]*(k-1) + dp[i+k][end] + (sum[end] - sum[i+k-1])*k);
}
}
}
printf("Case #%d: %d\n", ++z, dp[1][n]);
}
}
}