题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2136
I guess the n-queen problem is known by every person who has studied backtracking. In this problem you should count the number of placement of n queens on an n*n board so that no two queens attack each other. To make the problem a little bit harder (easier?), there are some bad squares where queens cannot be placed. Please keep in mind that bad squares cannot be used to block queens‘ attack.
Even if two solutions become the same after some rotations and reflections, they are regarded as different. So there are exactly 92 solutions to the traditional 8-queen problem.
8 ........ ........ ........ ........ ........ ........ ........ ........ 4 .*.. .... .... .... 0
Case 1: 92 Case 2: 1
n后问题的加强版,采用普通的回朔会超时,所以用状态压缩和位运算加以优化。
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<algorithm> #include<vector> using namespace std; const int MAX=20; int str[MAX];//原串 int n,msk; char s[MAX];//原串 int dfs(int dep,int dow,int lefd,int rigd){//dow,lefd,rigd表示上一层所能攻击到的区域 if(dep>=n) return 1; int cur=~( str[dep] | dow | lefd | rigd );//反转得到1表示这一层,可以放的地方,0表示这一层不可以放的地方。 int p=cur&(-cur)&msk;//搞到最后一个非0位 int ret=0; while(p){ ret+=dfs(dep+1,dow|p,(lefd|p)<<1,(rigd|p)>>1); cur^=p;//那位置0 p=cur&(-cur)&msk; } return ret; } int main(){ int cas=0; while(scanf("%d",&n),n){ msk=(1<<n)-1; for(int i=0;i<n;i++){ scanf("%s",s); str[i]=0; for(int j=0;s[j];j++){ if(s[j]=='*'){ str[i]|=(1<<j);//把不能访问的区域标志成1 } } } printf("Case %d: %d\n",++cas,dfs(0,0,0,0)); } return 0; }
uva 11195 Another queen (用状态压缩解决N后问题),布布扣,bubuko.com
uva 11195 Another queen (用状态压缩解决N后问题)
原文地址:http://blog.csdn.net/asdfghjkl1993/article/details/37738291