UVa 750 - 8 Queens Chess Problem
来源:互联网 发布:17年淘宝卖q币 编辑:程序博客网 时间:2024/04/28 04:11
题目:计算一定经过给定点的八皇后。
分析:搜索。因为八皇后只有92组解,直接计算出92组解,然后查询输出即可。
这里我使用了位运算来计算八皇后,减少代码量。
先考虑一个皇后的影响,每次下一层攻击的点和上一次的关系如下:
一个皇后会影响自己下方和左右两个斜的方向(从上往下搜索);
向左的斜的影响下一层向左移动一位,向右的影响向右移动一位;
因此,我们把三种影响分别用位表示,
L,M,R分别是三种情况的,之前所有皇后能攻击的点的位表示;
如果本次取第i个元素则三个元素对应位:
L =(L|(1<<i))<<1,M|(1<<i),(R|(1<<i))>>1;
这里我是枚举选取的元素,可以利用位运算求出最后的可用位(-p&p);
不过展开时麻烦点(因为是2^i,不是i)。
说明:注意编号有%2d输出。
#include <iostream>#include <cstdlib>#include <cstdio>using namespace std;int ans[92][9],temp[9];int Count = 0;void dfs(int L, int M, int R, int d){if (d == 8) {Count ++;return;}for (int i = 0 ; i < 8 ; ++ i) {if (((L|M|R)&(1<<i)) == 0) {for (int j = 0 ; j < d ; ++ j)temp[j] = ans[Count][j];ans[Count][d] = i+1;dfs((L|(1<<i))<<1, M|(1<<i), (R|(1<<i))>>1, d+1);for (int j = 0 ; j < d ; ++ j)ans[Count][j] = temp[j];}}}int main(){Count = 0;dfs(0, 0, 0, 0);int t,x,y;while (~scanf("%d",&t)) while (t --) {scanf("%d%d",&x,&y);printf("SOLN COLUMN\n");printf(" # 1 2 3 4 5 6 7 8\n\n");int count = 1;for (int i = 0 ; i < Count ; ++ i)if (ans[i][y-1] == x) {printf("%2d ",count ++);for (int j = 0 ; j < 8 ; ++ j)printf(" %d",ans[i][j]);printf("\n");}if (t) printf("\n");}return 0;}
0 0
- UVa 750 - 8 Queens Chess Problem
- 8 Queens Chess Problem
- 8 Queens Chess Problem
- 1 answer for 8 queens problem
- UVa 11085 - Back to the 8-Queens
- poj1321 Chess Problem
- poj-1321Chess Problem
- N-Queens Problem
- UVa 11538 - Chess Queen
- UVa 278 - Chess
- Chess Queen UVA 11538
- UVA 11538 Chess Queen
- Uva-11538-Chess Queen
- UVa 11538 Chess Queen
- UVa 11538 - Chess Queen
- uva 11538 Chess Queen
- UVA 11538 Chess Queen
- UVA 11538 - Chess Queen
- 毓脊承缸卵牡耪案偃壕估糠
- JNI Local Reference Changes in ICS
- Maven的安装和本地仓库初始化
- moo.fx.js之JS折叠菜单-使用方法
- 2014/9/30 《Python 灰帽子—黑客与逆向工程师的Python编程之道》学习
- UVa 750 - 8 Queens Chess Problem
- 移动视频开发包给我们带来的技术优势
- zigbee基本概念及组网特性
- 访问者模式的意图
- android4.1.2 DexClassLoader is not owned by the current user 问题
- CentOS上安装mysql5.5安装
- 嵌入式 linux下kernel代码中设备驱动模型之device
- TextBox自动匹配,自动完成,AutoCompleteCustomSource
- Service深入分析