ZOJ Monthly, November 2012 慎入











zoj 3675 :http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4918

bfs即可,指甲的每个状态都是一个节点,状态数最多为2^20

每次搜的方向可以枚举指甲钳放的位置

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
int n,m,goal;
char s[110];
queue<pair<int,int> > Q;
int clipper[2];
bool vis[1<<21];
int bfs()
{
	int i,j,k;
	fill(vis,vis+(1<<n),false);
	vis[0] = true;
	while(!Q.empty())
	{
		pair<int,int> node = Q.front();Q.pop();
		int state = node.first; int step = node.second;
		int s = state,to;
		for(k=0;k<2;k++)
		{
			for(i=n-1;i>=0;i--)
			{
				to = ((clipper[k] << i) | s) & goal;
				if(to == state || vis[to]) continue ;
				vis[to]=true;
				if(to == goal) return step+1;
				Q.push(make_pair(to,step+1));
			}
			for(i=1;i<=m-1;i++)
			{
				to = ((clipper[k] >> i) | s) & goal;
				if(to == state || vis[to]) continue;
				vis[to]=true;
				if(to == goal) return step+1;
				Q.push(make_pair(to,step+1));
			}
		}
	}
	return -1;
}
int main()
{
	int i,j,k;
    while(scanf("%d",&m)!=EOF)
	{
		clipper[0]=0;clipper[1]=0;
		scanf("%s",s);
		for(i=0;s[i];i++) if(s[i]=='*') clipper[0] |= 1<<(m-1-i),clipper[1] |= 1<<i;
		scanf("%d",&n);
		if(clipper == 0) 
		{
			puts("-1");
			continue;
		}
		goal = (1<<n)-1;
		while(!Q.empty()) Q.pop();
		Q.push(make_pair(0,0));
		int ans = bfs();
		printf("%d\n",ans);
	}
	return 0;
}


你可能感兴趣的:(ZOJ Monthly, November 2012 慎入)