洛谷P1219八皇后_位运算解法

#include<iostream>
#include<cstdio>
#include<cmath>
#include<bitset>
using namespace std;

#define lowbit(x) (x&(-x))  //取x的最低位

int n,mask;
int ans[15],cnt;

inline int loc(int x)
{
    int res=0;
    while(x>1) {x/=2;res++;}
    return res;
}

void func(int a,int b,int c,int r)
{
    if(r==n+1)
    {
        cnt++;
        if(cnt<=3)
        {
            for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
            cout<<"\n";
        }
        return;
    }
    int d=(~(a | b<<1 | c>>1))&mask;

    while(d)
    {
       int p=lowbit(d);
       if(p&mask==0) return;    //没有符合条件的位置
       d-=p;
       ans[r]=loc(p)+1;
       func(a|p,(b<<1)|p,(c>>1)|p,r+1);
    }

}

int main()
{
    cin>>n;
    mask=pow(2,n)-1;    //设置掩码,将超出n位的部分去掉
    //cout<<bitset<32>(mask);
    func(0,0,0,1);
    cout<<cnt<<"\n";
    return 0;
}

解释写在了注释里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值