题目
hdu4283
题意:
一些人排队上场表演,第 k 个上场表演的人有 k - 1 * a[i] 的代价,有一个小黑屋(即栈),每个人可以进去小黑屋或直接上场表演,又或者是从小黑屋那里出去一个人上场表演(小黑屋是后进先出)。问如何合理利用小黑屋来得到最小的代价。
思路:
在区间 i ~ j 内,a [ i ] 是第 k 个出场的,则区间 i+1 ~ i+k出场的代价 + a[i] * k + 区间 k+1 ~ j出场的代价 * (k+1)
d
p
[
i
]
[
j
]
=
min
k
=
i
j
d
p
[
i
+
1
]
[
k
]
+
d
p
[
k
+
1
]
[
j
]
+
k
∗
a
[
i
]
+
(
k
+
1
)
∗
(
s
u
m
[
j
]
−
s
u
m
[
k
]
)
dp[i][j] = \min_{k=i}^{j} dp[i+1][k] + dp[k+1][j] + k*a[i] + (k+1)*(sum[j]-sum[k])
dp[i][j]=k=iminjdp[i+1][k]+dp[k+1][j]+k∗a[i]+(k+1)∗(sum[j]−sum[k])
代码
#include <iostream>
#include <algorithm>
#define DEBUG freopen("_in.txt", "r", stdin); freopen("_out1.txt", "w", stdout);
#define CASEE int t; cin >> t; for (int ti = 1; ti <= t; ti++)
using namespace std;
const int MAXN = 110;
const int INF = 1e8;
int a[MAXN], dp[MAXN][MAXN], sum[MAXN];
void solve(){
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d", &a[i]);
sum[i] = sum[i-1] + a[i];
}
for (int len = 1; len < n; len++)
for (int i = 1; i <= n - len; i++){
int j = i + len;
dp[i][j] = INF;
for (int k = i; k <= j; k++)
dp[i][j] = min(dp[i][j], dp[i+1][k] + dp[k+1][j] + (k-i) * a[i] + (k-i+1) * (sum[j]-sum[k])); //是dp[i+1][k]而不是dp[i][k],因为a[i]不在dp[i][k]的计算范围内(后面有(k-i) * a[i])
}
printf("%d\n", dp[1][n]);
}
int main(){
CASEE{
printf("Case #%d: ", ti);
solve();
}
return 0;
}