zoj1505 双向bfs
2015-09-19 10:16
337 查看
#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; }
相关文章推荐
- UVa 1600:Patrol Robot(IDA*)
- iOS线程死锁分析
- CVTE C/C++开发工程师笔试题(一)
- 升级Xcode之后VVDocumenter-Xcode不能用的解决办法
- 二叉树按中序遍历顺序转换成双向链表
- awk 详解
- LINUX系统监控常用命令
- Android界面跳转以及界面之间的传值
- SQLState: 08001
- 第一篇博客
- Java知识整理(十)之SE.TCP通信(Server和Client源代码)
- 仿struts2实现action跳转
- noip2007 字符串展开 (模拟)
- 字符串数组排序
- Java知识整理(九)之SE.多线程
- [NSNull null]
- WPF--窗口的属性
- PagerSwitch tab样式加上下拉刷新(一)
- 8个让程序员追悔莫及的职业建议
- 基础知识之_int、NSInteger、NSUInteger、NSNumber的区别和联系