题目大意:桌子上有n本书,从左到右记录其每本书的高度,高度为25–32,如果把相邻的高度相同的书看成一个片段,并且定义该书架的混乱程度为该书架上的书的片段,为了整理书架上的书,最多可以取出k本书,然后再插回书架,问如何操作,才能使混乱度达到最低,输出最低的混乱度
解题思路:设dp[i][j][S][end]为扫描到了第i本书,操作了j次,剩下的书的状态为S,最后一本书为end的最低混乱度,这样就有两种方向了
1.前面的那本书和当前这本书的高度相等
那么dp[i][j][S][end] = dp[i-1][j][S][end]
2.前面的那本书和当前的这本书的高度不想等,也有两个方向
a.抽取这本书,那么dp[i][j+1][S][e] = dp[i-1][j][S][e]
b.不抽取这本书,那么dp[i][j][S | end][end] = dp[i-1][j][S][e] + 1
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
#define maxn (1<<8)
#define maxm 110
int dp[2][maxm][maxn][10], n, k;
int bitcount(int cur) {
return cur == 0 ? 0 : bitcount(cur/2) + (cur % 2);
}
int main() {
int mark = 1;
while(scanf("%d%d", &n, &k) == 2 && (n + k)) {
int S = 0, num, now, pre;
memset(dp[0],0x3f,sizeof(dp[0]));
for(int i = 0; i < n; i++) {
scanf("%d", &num);
num -= 25;
pre = i & 1;
now = !pre;
memset(dp[now],0x3f,sizeof(dp[now]));
dp[now][i][(1<<num)][num] = 1;
for(int j = 0; j <= min(i,k); j++)
for(int S0 = S; S0; S0 = (S0 - 1) & S)
for(int end = 0; (1 << end) <= S0; end++)
if(dp[pre][j][S0][end] != INF) {
if(end == num)
dp[now][j][S0][end] = min(dp[now][j][S0][end],dp[pre][j][S0][end]);
else {
dp[now][j+1][S0][end] = min(dp[now][j+1][S0][end], dp[pre][j][S0][end]);
dp[now][j][S0 | (1 << num)][num] = min(dp[now][j][S0 | (1 << num)][num], dp[pre][j][S0][end]+1);
}
}
S = S |(1 << num);
}
int ans = INF;
for(int j = 0; j <= k; j++)
for(int S0 = S; S0 ; S0 = (S0 - 1) & S)
for(int end = 0; (1 << end) <= S0; end++)
if(dp[n&1][j][S0][end] != INF)
ans = min(ans,dp[n&1][j][S0][end] + bitcount(S^S0));
printf("Case %d: %d\n\n",mark++, ans);
}
return 0;
}