Colored stones
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1734 | Accepted: 819 |
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, …, xmeach 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.
题目大意:有N≤100个石头排成一列,每个石头都有颜色编号≤5,求扔掉最少的石头,使得任意两个相同颜色的石头之间没有其他颜色的石头[多组数据]
题解:很明显的状态压缩DP,但我一开始竟然想到搜索剪枝(扔掉该扔的以后一定成了几个颜色的排列=5!,加点优化应该能过)
DP[i][j][k] 前 i 个 最后留下的石子颜色为 j 用 k 记录颜色的出现情况
囧。。。DP太神了。。不得不服!
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #include<vector> #include<stack> using namespace std; int m,k; int a[105],dp[105][6][(1<<5)+2]; int main() { while(scanf("%d%d",&m,&k)!=EOF) { if(m==0&&k==0) break; memset(dp,0,sizeof(dp)); for(int i=1;i<=m;i++) { scanf("%d",&a[i]); a[i]--; } for(int i=1;i<=m;i++) dp[i][a[i]][1<<a[i]]=1; for(int i=1;i<m;i++) { for(int j=0;j<k;j++) { for(int t=0;t<(1<<k);t++) { if(dp[i][j][t]) { int temp=dp[i][j][t]; int ret=a[i+1]; int ins=(1<<ret); if(ret==j) { dp[i+1][j][t]=max(dp[i+1][j][t],temp+1); } else if(ins&t) { dp[i+1][j][t]=max(dp[i+1][j][t],temp); } else { dp[i+1][j][t]=max(dp[i+1][j][t],temp); dp[i+1][ret][t|ins]=max(dp[i+1][ret][t|ins],temp+1); } } } } } int ans=1; for(int i=0;i<k;i++) { for(int j=0;j<(1<<k);j++) ans=max(ans,dp[m][i][j]); } printf("%d\n",m-ans); } return 0; }