洛谷 P1562 还是N皇后

传送门:https://www.luogu.com.cn/problem/P1562

参考博客:https://blog.csdn.net/qq_40828060/article/details/79364577

这题一开始用普通dfs,超时。

看大佬用位运算,我也来试试。不同的是,我用0表示不可放置,1表示可放置,那么,在dfs的参数传递时有点麻烦

dfs函数中,p中的1,表示该行放置的位置,在进一步dfs时,考虑到对下一行的影响,~p才表示可放置的位置。

在同一列的角度,应当是当前列&~p:row&~p

在主对角线(left diagonal),应当是(当前状态&~p)>>1,再高位补1,注意此时补的1应当为(1<<N>>1)

在次对角线(right diagonal),应当是(当前状态&~p)<<1,再低位补1,此时补的1是真的1。

不得不说,这么做非常麻烦,还是可放置用0表示,不可放置用1表示方便写程序。

我倔强地debug了2个多小时才把位运算这里搞完。唉,太菜了。!!!

#include <stdio.h>
#include <stdlib.h>

int N;
int ans;
int map[15];
int allone;
void dfs(int i,int row,int ld,int rd);
int main(void) {

    char ch[16];
    int i,j;

    scanf("%d\n",&N);

    allone=(1<<N)-1;
    for(i=0; i<N; i++) {
        gets(ch);
        for(j=0; j<N; j++) {
            map[i]=(ch[j]== '*')+(map[i]<<1);
        }
    }

    dfs(0,allone,allone,allone);

    printf("%d",ans);
    return 0;
}
void dfs(int i,int row,int ld,int rd) {
    int pos,p;
    if(i==N) {
        ans++;
        return;
    }

    pos=allone&(map[i]&row&ld&rd);
    while(pos) {
        p=pos&(-pos);
        pos-=p;
        dfs(i+1,row&~p,1+((ld&~p)<<1),(1<<N>>1)+((rd&~p)>>1));//左移低位补1,右移低位补0
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

字江慕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值