Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1778 | Accepted: 838 |
Description
You are given a row of m stones each of which has one of k different colors. What is the minimum number of stones you must remove so that no two stones of one color are separated by a stone of a different color?
Input
The input test file will contain multiple test cases. Each input test case begins with a single line containing the integers m and k where 1 ≤ m ≤ 100 and 1 ≤ k ≤ 5. The next line contains m integers x1, …, xm each of which takes on values from the set {1, …, k}, representing the k different stone colors. The end-of-file is marked by a test case with m = k = 0 and should not be processed.
Output
For each input case, the program should the minimum number of stones removed to satisfy the condition given in the problem.
Sample Input
10 3 2 1 2 2 1 1 3 1 3 3 0 0
Sample Output
2
Hint
In the above example, an optimal solution is achieved by removing the 2nd stone and the 7th stone, leaving three “2” stones, three “1” stones, and two “3” stones. Other solutions may be possible.
Source
想到了其实还是比较简单的状压dp,f[i][s0][k]表示要将i号石头加入序列时,此时序列的颜色集合为j状态,且集合最后一个石头的颜色为k号的序列的最大长度,最后答案就是初始序列长度n减去max(f[n][s0][k])
这道题的巧妙之处就在于没有直接的求出答案,而是间接地求出了一个能够到达的最大长度,是比较经典的一道题
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxm=105,maxk=(1<<7);
int m,n,f[3][maxk][7];
int main(){
while(scanf("%d%d",&n,&m)&&(n||m)){
int all=(1<<m)-1,i,s0,k,x;
memset(f,0,sizeof(f));
for(i=1;i<=n;i++){
scanf("%d",&x);
x--;//从0开始编号
for(s0=0;s0<=all;s0++)
if(!(s0&(1<<x)))//如果当前颜色不在集合中
for(k=0;k<m;k++){
f[i&1][s0|(1<<x)][x]=max(f[i&1][s0|(1<<x)][x],f[(i+1)&1][s0][k]+1);//选这个石头
f[i&1][s0][k]=max(f[i&1][s0][k],f[(i+1)&1][s0][k]);//不选这个石头
}
else //如果当前颜色已经出现过
for(k=0;k<m;k++)
if(k==x)
f[i&1][s0][k]=max(f[i&1][s0][k],f[(i+1)&1][s0][k]+1);//选这个石头
else
f[i&1][s0][k]=max(f[i&1][s0][k],f[(i+1)&1][s0][k]);//不选这个石头
}
int ans=0;
for(s0=0;s0<=all;s0++)//枚举最大长度
for(i=0;i<m;i++)
ans=max(ans,f[n&1][s0][i]);
cout<<n-ans<<endl;
}
}