zoj1505 双向bfs

#include <set>
#include <map>
#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <iostream>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define FOR(i,s,t) for(int i=(s); i<(t); i++)
#define BUG puts("here!!!")
#define STOP system("pause")
#define file_r(x) freopen(x, "r", stdin)
#define file_w(x) freopen(x, "w", stdout)


using namespace std;


typedef long long LL;


int isok(int x,int y){
	if( x >= 0 && x < 8 && y >= 0 && y < 8)
		return 1;
	return 0;
}
void pro(LL &st)
{
	int x, y;
	scanf("%d%d", &x, &y);
	x--; y--;
	int p = x * 8 + y;
	st |= (1ll << p);	
}


queue< pair<LL,int> > q;
set<LL> sets, sett;
set<LL>::iterator it; //用set可以避免bfs重复访问某个点 
int dir[9] = {1,0, -1,0, 0,1, 0,-1};
bool Bin(LL st, int t, set<LL> &s, set<LL> &ss, bool f)
{
	bool a[100][100];
	int p[5][5], cnt = 0;
	memset(a, false, sizeof(a));
	FOR(i, 0, 64)
		if( st & (1ll << i) )
		{
			int x = i/8;
			int y = i%8;
			a[x][y] = true;
			p[cnt][0] = x;
			p[cnt++][1] = y;
		}
	FOR(i, 0, 4) //跳哪一颗 
	{
		LL tmp = st;
		tmp -= (1ll << (p[i][0]*8 + p[i][1])); //这一颗棋子要跳走了 
		LL la = tmp;
		for(int k=0; k<8; k+=2) //往什么方向 
		{
			tmp = la;
			int x = p[i][0] + dir[k];
			int y = p[i][1] + dir[k+1];
			if(isok(x,y)&&a[x][y]){
				x += dir[k];
				y += dir[k+1];   //跳一格 
			}
			if(!isok(x,y)||a[x][y])  continue;
			tmp += (1ll << (x * 8 + y));  
			if( !s.count(tmp) )
			{
				if( f && ss.count(tmp) ) return true;//f:正向正常搜索,反向判断 
				if(!s.count(tmp)) //剪枝 
					q.push(make_pair(tmp, t));
				s.insert(tmp);
			}
		}
	}
	return false;
}


bool BFS(LL st, set<LL> &s, set<LL> &ss, bool f)
{
	s.clear();
	while( !q.empty() ) q.pop();
	s.insert(st);
	q.push(make_pair(st, 0));
	
	while( !q.empty() )
	{
		if( q.front().second < 4 )  //正反都扩展4层,复杂度2*16^4 
		{
			bool ans = Bin(q.front().first, q.front().second + 1, s, ss, f);
			if( ans ) return true;
		}
		else
			return false;
		q.pop();
	}
	return false;
}
	
bool solve(LL st, LL tt)
{
	BFS(st, sets, sett, false);
	return BFS(tt, sett, sets, true);
}


int main()
{
	LL st, tt;
	int x, y;
	
	while( ~scanf("%d%d", &x, &y) )
	{
		st = tt = 0;
		x--; y--;
		int p = x * 8 + y;
		st += (1ll << p);
		
		FOR(i, 0, 3) pro( st );
		FOR(i, 0, 4) pro( tt );
		
		bool ans = solve(st, tt);
		
		puts(ans ? "YES" : "NO");
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值