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 (1 <= k <= 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
题意:一个人有n本书,每本书有自己的高度x,范围是【25,32】,同时题目规定一段连续的高度的书的混乱度为1,不连续的高度的书混乱度也为1,然后现在给你k次操作移动某些书到任意位置,请问k次操作后所有书的最小混乱值。
思路:这道题的话,我们根据题意,能想到用状压DP去做,然后我们想一下状态。我们设dp[i][j][s][x],表示前i本书中,我们拿了j本,没拿的书的集合是s,没拿的书的最后一本是x的最优解。我们为什么状态压缩的是目前桌子上的书的集合,是因为我们要防止一种情况:那就是如果对于高度为h的一种书, 我们都拿走了, 那么还要放回桌子上, 最优解要+1, 这样表示之后, 我们只要判断一下有几种书桌子上没有就行了。
然后状态转移的话,我们设当前这本书为x,上一本书为p。分为两种情况讨论:
1:当p==x的时候,这时候肯定不能取走
2:当p!=x的时候,又要分两种情况:
1):不取走当前这本书
2):取走当前这本书
因为我们求的是剩下的书的混乱度,所以还要加上取走的书的混乱度。
最后,这道题谜之卡内存,是一道好题!!!
AC代码:
#include <bits/stdc++.h>
typedef long long ll;
const int maxx=110;
const int inf=0x3f3f3f3f;
using namespace std;
int dp[2][maxx][1<<8][10];
int main()
{
int n,k,num=1;
while(~scanf("%d%d",&n,&k),n,k)
{
memset(dp,inf,sizeof(dp));
int a,b,x;
a=b=0;
for(int i=0; i<n; i++)
{
scanf("%d",&x);
x-=25;
a^=1;
memset(dp[a],inf,sizeof(dp[a]));
dp[a][i][1<<x][x]=1;
for(int j=0; j<=min(i,k); j++)
{
for(int s=b; s; s=(s-1)&b)
{
for(int p=0; (1<<p)<=s; p++)
{
if(dp[a^1][j][s][p]!=inf)
{
if(p==x)
dp[a][j][s][p]=min(dp[a][j][s][p],dp[a^1][j][s][p]);
else
{
dp[a][j][s|(1<<x)][x]=min(dp[a][j][s|(1<<x)][x],dp[a^1][j][s][p]+1);
dp[a][j+1][s][p]=min(dp[a][j+1][s][p],dp[a^1][j][s][p]);
}
}
}
}
}
b|=(1<<x);
}
int ans=inf;
int cnt;
for(int j=0; j<=k; j++)
{
for(int s=b; s; s=(s-1)&b)
{
for(int p=0; (1<<p)<=s; p++)
{
if(dp[a][j][s][p]!=inf)
cnt=0;
for(int y=s^b; y; y&=(y-1))
cnt++;
ans=min(ans,dp[a][j][s][p]+cnt);
}
}
}
printf("Case %d: %d\n\n",num++,ans);
}
return 0;
}