题目大意是给12个空槽,初始时有以下空槽中有石头,可以把两个连续的石头移动到相邻的一个空槽,并移调中间的石头,求最少剩余几块石头。
用一个整数表示状态,因公也就不到10000种状态,数组记录即可,状态转移用位操作即可。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define lowbit(x) x&(-x)
using namespace std;
int dp[10000];
int dfs(int st)
{
if(dp[st]!=-1) return dp[st];
int op=7,r1=3,r2=6,tt=st;
dp[st]=0;
while(tt) {dp[st]++;tt^=(lowbit(tt));}
while(op<=3584){
int temp=st&op;// 获取局部状态
if(temp==r1||temp==r2) dp[st]=min(dp[st],dfs(st^op));// 若可以消去石头,则尝试更新
op<<=1;r1<<=1;r2<<=1;
}
return dp[st];
}
int main()
{
int n;
cin>>n;getchar();
while(n--){
memset(dp,-1,sizeof(dp));
int st=0;
char t;
for(int i=0;(t=getchar())!='\n';i++){
st|=((t=='-'?0:1)<<i);
}
dfs(st);
cout<<dp[st]<<endl;
}
return 0;
}