UVa #11214 Guarding the Chessboard (习题7-10)
来源:互联网 发布:mac天津专柜地址 编辑:程序博客网 时间:2024/06/10 11:10
被TLE的阴影笼罩了一周,放一道上周刷的小水题开开心先。。之前有人说UVa的数据比较苛刻,现在有点体会了,不优化就是跪,优化的不够还是跪。另外发现有些题目的Stat是不太准啊,明明很难的题90%多的user solving rate,明明很水的题,比如这道保卫棋盘,却只有27.7%、69.9%。。。
回归正题:
这道保卫棋盘跟八皇后问题如出一辙,所以尝试沿用一下回溯法。在回溯法深度优先遍历解答树的同时,要使皇后数量最少,(又因为最大深度并不会太深)迭代加深搜索就是很漂亮的解法了。
剩下的就很简单了,vis数组要开4维,分别对应行、列、主对角线和副对角线。
Run Time: 0.579s
#define UVa "7-10.11214.cpp"#include<cstring>#include<cstdio>#include<string>using namespace std;//Global Variables.int n, m, kase = 0;int vis[4][30]; //row, col, diag1, diag2int targ[10][10];/////void init() { char ch; memset(targ, 0, sizeof(targ)); for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { do{scanf("%c", &ch);}while(!isprint(ch)); if(ch == 'X') { targ[i][j] = 1; } } }}int arrvied() { for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { if(targ[i][j] && !vis[0][i] && !vis[1][j] && !vis[2][i+j] && !vis[3][n+j-i]) return 0; } } return 1;}int dfs(int d, int cur, int maxd) { if(d == maxd) { if(arrvied()){ printf("Case %d: %d\n", ++kase, d); return 1; } return 0; } else { //Need for pruning? for(int pos = cur; pos < n*m; pos ++) { int r = pos/m, c = pos%m; int tmp_a = vis[0][r], tmp_b = vis[1][c], tmp_c = vis[2][r+c], tmp_d = vis[3][c-r+n]; vis[0][r] = vis[1][c] = vis[2][r+c] = vis[3][c-r+n] = 1; if(dfs(d+1, pos, maxd)) return 1; vis[0][r] = tmp_a; vis[1][c] = tmp_b; vis[2][r+c] = tmp_c; vis[3][c-r+n] = tmp_d; } } return 0;}int main() { while(scanf("%d%d", &n, &m) == 2 && n && m) { init(); for(int maxd = 0; ; maxd ++) { memset(vis, 0, sizeof(vis)); if(dfs(0, 0, maxd)) break; } } return 0;}
0 0
- UVa #11214 Guarding the Chessboard (习题7-10)
- 习题7-10 UVA 11214 Guarding the Chessboard (迭代加深搜索)
- UVa 11214 Guarding the Chessboard
- UVa 11214 - Guarding the Chessboard
- UVA 11214 Guarding the Chessboard
- UVa 11214 - Guarding the Chessboard
- Guarding the Chessboard UVA
- Guarding the Chessboard UVA
- Guarding the Chessboard UVA
- Uva11214 Guarding the Chessboard【dfs回溯】【习题7-10】
- UVa 11214:Guarding the Chessboard(DFS)
- UVA 11214(p217)----Guarding the Chessboard
- UVA 11214 Guarding the Chessboard(回溯)
- 11214 - Guarding the Chessboard
- UVa 11214 - Guarding the Chessboard(迭代加深搜索)
- 11214 - Guarding the Chessboard(暴力搜索)
- UVa11214 - Guarding the Chessboard
- Guarding the Farm
- Ant 打 war 包过程
- 015 do-while语句
- CAS修改源码支持多种方式登录认证
- 轻松Scrum之旅(下)
- C#多线程指纹比对
- UVa #11214 Guarding the Chessboard (习题7-10)
- birt报表用rptlibrary统一所有报表的数据源
- pb数据窗口saveas成xml的时候返回-1的问题处理
- ant 部署war包到tomcat,weblogic服务器上
- 浅谈怎样提高百度空间排名(非原创)
- 新网站产生上万流量的办法
- 关于清理系统垃圾的bat
- RHEL64 缺少ISO 9660图像 安装程序试图挂载映像#1,在硬盘上无法找到该映像
- 解决Win2003 server sp1安装IIS组件无法复制文件的问题