原题: ZOJ 3675 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3675
由m<=20可知,可用一个二进制数表示指甲的状态,最多2^20,初始状态为0,表示指甲都没剪,然后BFS找解,每次枚举剪刀的两个方向,枚举移动的位数进行扩展状态即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
#define N 10007 struct node
{
int state,step;
node(int _state,int _step)
{
state = _state;
step = _step;
}
node(){}
}; int vis[<<];
int cut[]; //两个方向
queue<node> que;
int n,m; int bfs(int s)
{
int i,j,k;
memset(vis,,sizeof(vis));
while(!que.empty())
que.pop();
int E = (<<m)-;
que.push(node(s,));
vis[s] = ;
while(!que.empty())
{
node tmp = que.front();
que.pop();
int state = tmp.state;
int step = tmp.step;
int tms = state;
for(i=;i<;i++) //direction
{
for(j=;j<n;j++) //move
{
int end = ((cut[i]>>j) | tms) & E; // &E : keep m bit
if(vis[end])
continue;
vis[end] = ;
if(end == E)
return step+;
que.push(node(end,step+));
}
for(j=;j<m;j++)
{
int to = ((cut[i]<<j) | tms) & E;
if(vis[to])
continue;
vis[to] = ;
if(to == E)
return step+;
que.push(node(to,step+));
}
}
}
return -;
} int main()
{
int i,j;
char ss[];
while(scanf("%d",&n)!=EOF)
{
cut[] = cut[] = ;
scanf("%s",ss);
for(i=;i<=n;i++)
{
if(ss[i] == '*')
{
cut[] |= (<<i);
cut[] |= (<<(n--i));
}
}
scanf("%d",&m);
if(cut[] == )
{
puts("-1");
continue;
}
printf("%d\n",bfs());
}
return ;
}