Bubu's bookshelf is in a mess! Help him!
There are n books on his bookshelf. We define the mess value to be the number of segments of consecutive equal-height books. For example, if the book heights are 30, 30, 31, 31, 32, the mess value is 3, that of 30, 32, 32, 31 is also 3, but the mess value of 31, 32, 31, 32, 31 is 5 -- it's indeed in a mess!
Bubu wants to reduce the mess value as much as possible, but he's a little bit tired, so he decided to take out at most k books, then put them back somewhere in the shelf. Could you help him?
Input
There will be at most 20 test cases. Each case begins with two positive integers n and k (1k
n
100), the total number of books, and the maximum number of books to take out. The next line contains n integers, the heights of each book, from left to right. Each height is an integer between 25 and 32, inclusive. The last test case is followed by n = k = 0, which should not be processed.
Output
For each test case, print the case number and the minimal final mess value. Print a blank line after the output of each test case.
Sample Input
5 2 25 25 32 32 25 5 1 25 26 25 26 25 0 0
Sample Output
Case 1: 2 Case 2: 3
题意:布布有25-32高度的书本,相同一堆的书本杂乱度为1,现在他可以取k次书本重新放回,问整理后最少的杂乱度是多少。
思路:书本只有8种,可以用状态压缩DP,我们先把每本书分取和不取,取完之后会有一个杂乱度,由于书本又要放回,所以总杂乱度为(取完的杂乱度 + 放回的书是否在剩下的书中有)。
dp[i][j][s][k]表示取第i本书,第j次,当前剩下书的集合s,最后一本书为k。
那么状态转移方程为:如果当前书和最后一本相同,不取肯定最好dp[i][j][s][book] = min(dp[i][j][s][book], dp[i - 1][j][s][k]);
如果不同就分为取与不取考虑。如果不取杂乱度+1.
不取:dp[i][j][s|(1<<book)][book] = min(dp[i][j][s|(1<<book)][book], dp[i - 1][j][s][k] + 1);
取:dp[i][j + 1][s][k] = min(dp[i][j + 1][s][k], dp[i - 1][j][s][k]);
由于四维数组很大,要利用滚动数组去优化,0,1表示now或nex的情况。
代码:
#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
#define min(a,b) ((a)<(b)?(a):(b))
const int N = 105;
const int M = 8;
const int MAXM = (1<<8);
int n, K, book, dp[2][N][MAXM][M], st;
int bitcount(int x) {
if (x == 0) return 0;
return bitcount(x>>1) + (x&1);
}
int solve() {
int ans = INF;
st = 0; int i, j, s, k;
memset(dp[0], INF, sizeof(dp[0]));
for (i = 0; i < n; i++) {
scanf("%d", &book);
book -= 25;
int now = i&1;
int nex = !now;
memset(dp[nex], INF, sizeof(dp[nex]));
dp[nex][i][(1<<book)][book] = 1;
for (j = 0; j <= i && j <= K; j++) {
for (s = st; s; s = (s - 1)&st) {
for (k = 0; (1<<k) <= s; k++) {
if (dp[now][j][s][k] == INF) continue;
if (k == book) {
dp[nex][j][s][book] = min(dp[nex][j][s][book], dp[now][j][s][k]);
}
else {
dp[nex][j][s|(1<<book)][book] = min(dp[nex][j][s|(1<<book)][book], dp[now][j][s][k] + 1);
dp[nex][j + 1][s][k] = min(dp[nex][j + 1][s][k], dp[now][j][s][k]);
}
}
}
}
st = (st|(1<<book));
}
for (j = 0; j <= K; j++) {
for (s = st; s; s = (s - 1)&st) {
for (k = 0; (1<<k) <= s; k++) {
if (dp[n&1][j][s][k] == INF) continue;
ans = min(ans, bitcount(st^s) + dp[n&1][j][s][k]);
}
}
}
return ans;
}
int main() {
int cas = 0;
while (~scanf("%d%d", &n, &K) && n + K) {
printf("Case %d: %d\n\n", ++cas, solve());
}
return 0;
}