UVa 11085 - Back to the 8-Queens
来源:互联网 发布:nginx负载均衡 编辑:程序博客网 时间:2024/04/28 22:51
题目:给你一个棋盘上的八个皇后,每行一个,现在让他们互相不攻击,每个皇后只能竖着移动,
一次可以移动到本列的任何位置,问最少移动几步,能满足要求。
分析:搜索,八皇后。因为八皇后只有92组解,直接计算出92组解,然后找出不在对应最少的一组解。
这里我使用了位运算来计算八皇后,减少代码量。
先考虑一个皇后的影响,每次下一层攻击的点和上一次的关系如下:
一个皇后会影响自己下方和左右两个斜的方向(从上往下搜索);
向左的斜的影响下一层向左移动一位,向右的影响向右移动一位;
因此,我们把三种影响分别用位表示,
L,M,R分别是三种情况的,之前所有皇后能攻击的点的位表示;
如果本次取第i个元素则三个元素对应位:
L =(L|(1<<i))<<1,M|(1<<i),(R|(1<<i))>>1;
这里我是枚举选取的元素,可以利用位运算求出最后的可用位(-p&p);
不过展开时麻烦点(因为是2^i,不是i)。
说明:注意回溯要保存状态,好久么刷题了╮(╯▽╰)╭。
#include <cstdlib>#include <cstring>#include <cstdio>int ans[92][8], temp[8], size = 0;void dfs(int d, int L, int M, int R){if (d == 8) {size ++;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[size][j];ans[size][d] = i+1;dfs(d+1, (L|(1<<i))<<1, M|(1<<i), (R|(1<<i))>>1);for (int j = 0; j < d; ++ j)ans[size][j] = temp[j];}}int main(){size = 0;dfs(0, 0, 0, 0);int cases = 1; while (~scanf("%d",&temp[0])) {for (int i = 1; i < 8; ++ i) scanf("%d",&temp[i]); int min = 8; for (int i = 0; i < size; ++ i) {int count = 8; for (int j = 0; j < 8; ++ j) count -= (temp[j]==ans[i][j]); if (min > count) min = count;} printf("Case %d: %d\n",cases ++,min); } return 0;}
0 0
- UVa 11085 - Back to the 8-Queens
- ZOJ3582 Back to the Past
- ZOJ3582---Back to the Past
- The Prisoner of Zenda——8、Back to Zenda
- PKU3239 Solution to the n Queens Puzzle
- POJ3239 Solution to the n Queens Puzzle
- uva 10071 Back to High School Physics
- UVA 10071 - Back to High School Physics
- uva-10071 - Back to High School Physics
- uva 10071 Back to High School Physics
- UVa 10071 - Back to High School Physics
- UVA 10071 Back to High School Physics
- UVA:10071 - Back to High School Physics
- uva 10071 Back to High School Physics
- uva-10071-Back to High School Physics
- uva 10071 Back to High School Physics
- UVA 10071 Back to High School Physics
- UVA - 10071 - Back to High School Physics
- 辛星浅析PL/pgsql语法(上)
- 第一天 纪念一下
- css页面布局
- Web前端开发规范手册
- 通过VMware Workstation克隆文件
- UVa 11085 - Back to the 8-Queens
- CSS--利用CSS实现一个简易的二级菜单(仿京东)
- 博客感想
- Apache ab测试 Apache优于 nginx
- switch语句
- Table 对象集合
- hadoop2.7.0实践- WordCount
- while循环
- java设计模式(2)------DAO模式