Root | |
10651 - Pebble SolitaireTime limit: 3.000 seconds |
In this problem, we look at a simple variant of this game, namely a board with twelve cavities located along a line. In the beginning of each game, some of the cavities are occupied by pebbles. Your mission is to find a sequence of moves such that as few pebbles as possible are left on the board.
Input
The input begins with a positive integer n on a line of its own. Thereafter n different games follow. Each game consists of one line of input with exactly twelve characters, describing the twelve cavities of the board in order. Each character is either ‘-’ or ‘o’ (The fifteenth character of English alphabet in lowercase). A ‘-’ (minus) character denotes an empty cavity, whereas a ‘o’ character denotes a cavity with a pebble in it. As you will find in the sample that there may be inputs where no moves is possible.
Output
For each of the n games in the input, output the minimum number of pebbles left on the board possible to obtain as a result of moves, on a row of its own.
Sample Input
5
---oo--------
-o--o-oo----
-o----ooo---
oooooooooooo
oooooooooo-o
Sample Output
1
2
3
12
1
题意是棋类游戏,如果两颗棋子挨着,并且有一颗棋子的旁边是空着的,那么这颗棋子就可以越过另一颗棋子达到另一个位置,被越过的棋子当然不堪其辱,选择死亡,类似于这两种情况oo-或-oo,问最后剩下的棋子有多少。
首先,%一下写出此代码的人,代码优美的无可挑剔,几十行的代码运用状压巧妙的化简到十几行,虽然可读性差了一点点,但做多了状压就会一眼看出来,总之,此代码堪称完美。
总共有12个位置,可以状压来枚举每一种情况,首先需要记录下总共有多少个棋子,然后把能丢掉的棋子一个一个减去,最后得到结果。
记录棋子个数就直接用状态表示,然后求总棋子数的话只需要得到map[o]=='o'就让sum>>2就ok,然后剩下的怎么办,dfs记忆化搜索啊。把每一种状态dfs搜索,然后比较是否可以去掉这个棋子,如果可以去掉就直接枚举去掉后的下一种状态。这里需要定义一个值为12,即最多的石子数就是12,然后每次取去掉石子后最小的值。若是最后的值还是12,说明没有棋子可以消灭,枚举一下,输出最后答案就可以。
总之,位运算很难讲,还是看代码实现,自己多转化一下试试看。
代码实现:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<cstdio>
#define ll long long
#define mset(a,x) memset(a,x,sizeof(a))
using namespace std;
const double PI=acos(-1);
const int inf=0x3f3f3f3f;
const double esp=1e-6;
const int maxn=105;
const int mod=1e9+7;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll inv(ll b){if(b==1)return 1; return (mod-mod/b)*inv(mod%b)%mod;}
ll fpow(ll n,ll k){ll r=1;for(;k;k>>=1){if(k&1)r=r*n%mod;n=n*n%mod;}return r;}
char map[100];
int dfs(int s)
{
int minn=12;
for(int i=0;i<10;i++) //最后两位无论什么情况都不可以被枚举
{
if(((s>>i)&7)==6||((s>>i)&7)==3) //&7==6为oo-情况,&7==3为-oo的情况
minn=min(minn,dfs(s^(7<<i))); //取较小值,dfs后一种状态
}
if(minn==12) //没有得到可以删去的
{
for(int i=0;i<12;i++)
minn-=!(s&(1<<i)); //对比每一位,不是棋子的就减去
}
return minn; //返回最小值
}
int main()
{
int n,i,j,k;
scanf("%d",&n);
getchar();
while(n--)
{
gets(map);
int sum=0;
for(i=0;i<12;i++)
{
sum=(sum<<1); //得到最大值
if(map[i]=='o') //更新
sum++;
}
printf("%d\n",dfs(sum));
}
return 0;
}