uva 11195 Another queen (用状态压缩解决N后问题)

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2136


Problem A

Another n-Queen Problem

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.

Input

The input consists of at most 10 test cases. Each case contains one integers n (3 < n < 15) in the first line. The following n lines represent the board, where empty squares are represented by dots '.', bad squares are represented by asterisks '*'. The last case is followed by a single zero, which should not be processed.

Output

For each test case, print the case number and the number of solutions.

Sample Input

8
........
........
........
........
........
........
........
........
4
.*..
....
....
....
0

Output for the Sample Input

Case 1: 92
Case 2: 1

Rujia Liu's Present 1: A Tiny Contest of Brute Force


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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值