zoukankan      html  css  js  c++  java
  • 4.3.6 N皇后问题

    Problem Description
    在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
    你的任务是,对于给定的N,求出有多少种合法的放置方法。
     

    Input
    共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
     

    Output

                共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
     

    Sample Input
    1
    8
    5
    0
     

    Sample Output
    1
    92
    10
     

    Author
    cgf

    再熟悉不过的问题,不过从来没有认真研究过位运算,元旦期间想了两天,想通了,推荐Matrix67的位运算教程,挺详细的,不过要自己慢慢悟,几分钟就想出来的那不靠谱

     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <iostream>
     4 using namespace std;
     5 
     6 int anst=0,upperlimit,n,cnt,step=0,ans[11];
     7 
     8 void close()
     9 {
    10 exit(0);
    11 }
    12 
    13 void dfs(int row,int ld,int rd)
    14 {
    15     if (row==upperlimit)
    16     {
    17         anst++;
    18         return;
    19     }
    20     int could =upperlimit & (~(row|ld|rd));
    21     while (could!=0)
    22     {
    23         int t=could & (-could);
    24         could-=t;
    25         dfs(row+t,(ld+t)<<1,(rd+t)>>1);
    26     }
    27 }
    28 
    29 void init()
    30 {
    31 for (int i=1;i<=10;i++)
    32 {
    33 upperlimit=(1<<i)-1;
    34 anst=0;
    35 dfs(0,0,0);
    36 ans[i]=anst;
    37 }
    38 
    39 while (cin>>n)
    40 {
    41     if (n==0) break;
    42 cout<<ans[n]<<endl;    
    43 }
    44 
    45 }
    46 
    47 int main ()
    48 {
    49 init();
    50 close();
    51 return 0;
    52 }
  • 相关阅读:
    拉普拉斯矩阵
    正定矩阵 和 半正定矩阵
    Random Walk
    论文解读(DGI)《DEEP GRAPH INFOMAX》
    python安装easyinstall/pip出错
    pip国内源设置
    在Jupyter Notebook添加代码自动补全功能
    [BUUCTF]PWN——bjdctf_2020_babystack2
    [BUUCTF]REVERSE——[BJDCTF 2nd]8086
    [BUUCTF]PWN——jarvisoj_tell_me_something
  • 原文地址:https://www.cnblogs.com/cssystem/p/2843278.html
Copyright © 2011-2022 走看看