标签:space can tom 依次 leave dir sam attr 需要
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?
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)
For each test case, output the least summary of unhappiness .
2512345554322
Case #1: 20Case #2: 24
之前还需要做两个预处理,求一个sum[i][j]数组代表[i, j]上D的总和,和一个数组g[i][j]代表[i, j]依次入栈后倒序出栈的代价,都可用递推求出;
因此就有了状态转移方程:
dp(i, j) = min{g(i, j), mini<=k<j{dp(i, k)+dp(k+1, j)+sum(k+1, j)*(k-i+1), dp(k+1, j)+g(i, k)+sum(i, k)*(j-k)}}。
Code:
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define M(a) memset(a, 0, sizeof(a)); 4 const int MAXN = 100 + 10; 5 __int64 a[MAXN], dp[MAXN][MAXN], sum[MAXN][MAXN], g[MAXN][MAXN]; 6 7 int main() { 8 int T, n, icase = 0; 9 scanf("%d", &T); 10 while(T--) { 11 M(a);M(dp);M(sum);M(g); 12 scanf("%d", &n); 13 for (int i = 1; i <= n; ++i) scanf("%I64d", &a[i]); 14 for (int i = 1; i <= n; ++i) 15 for (int j = i; j <= n; ++j) 16 sum[i][j] = sum[i][j-1] + a[j]; 17 for (int i = n; i >= 1; --i) 18 for (int j = i; j >= 1; --j) 19 g[j][i] = g[j+1][i] + (i-j) * a[j]; 20 for (int l = 1; l <= n; ++l) 21 for (int i = 1; i + l - 1 <= n; ++i) { 22 int j = i + l - 1; 23 dp[i][j] = g[i][j]; 24 for (int k = i; k < j; ++k) 25 dp[i][j] = min(dp[i][j], min(dp[i][k]+dp[k+1][j]+sum[k+1][j]*(k-i+1), dp[k+1][j]+g[i][k]+sum[i][k]*(j-k))); 26 } 27 printf("Case #%d: %I64d\n", ++icase, dp[1][n]); 28 } 29 30 return 0; 31 }
HDU-4283 You Are the One (区间DP)
标签:space can tom 依次 leave dir sam attr 需要
原文地址:http://www.cnblogs.com/robin1998/p/6366426.html