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;
}

你可能感兴趣的:(zoj1505 双向bfs)