uva10651 - Pebble Solitaire(状态压缩)

状态压缩+记忆化搜索

状态压缩对位运算要求的较多。对位运算不熟的话就复习一下吧。

纯正的暴力然后用记忆化搜索剪枝。

碰到合适的情况就转移。【向右或向左】

求最后在棋盘上剩余最少的棋子数目。

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 4500
int dp[N];
char s[25];
int dfs(int total)
{
    int &ans = dp[total], temp;
    if(ans!=-1) return ans;
    ans = 0;
    for(int i = 0; i < 12; i++) if(total&1<<i)
    ans+=1;
    for(int i = 0; i < 10; i++)
    {
        temp = total;
        if((total&1<<i)&&(total&1<<(i+1))&&!(total&1<<(i+2)))
        {
            temp&=~(1<<i);
            temp&=~(1<<(i+1));
            temp|=(1<<(i+2));
            ans = min(ans,dfs(temp));
        }
        temp = total;
        if(!(total&1<<i)&&(total&1<<(i+1))&&(total&1<<(i+2)))
        {
            temp&=~(1<<(i+2));
            temp&=~(1<<(i+1));
            temp|=(1<<i);
            ans = min(ans,dfs(temp));
        }
    }
    return ans;
}
int main ()
{
    int total, cas;
    scanf("%d",&cas);getchar();
    while(cas--)
    {
        memset(dp,-1,sizeof(dp));
        scanf("%s",s);getchar();
        total = 0;
        for(int i = 0; i < 12; i++)
        {
            if(s[i]=='o')
            total^=(1<<i);
        }
        printf("%d\n",dfs(total));
    }
    return 0;
}


 

你可能感兴趣的:(uva10651 - Pebble Solitaire(状态压缩))