zoukankan      html  css  js  c++  java
  • 洛谷 1219:八皇后 (位运算 & DFS)

    题目链接: https://www.luogu.org/problem/show?pid=1219#sub

    row:受上面的皇后通过列控制的位置

    ld:受上面的皇后通过从右至左的斜对角线控制的位置

    rd:受上面的皇后通过从左至右的斜对角线控制的位置

    upperlim:每一列都被控制时row的状况

     1 #include <cstdio>
     2 using namespace std;
     3 int upperlim, c, cnt, sum, ans[4][20], a[20], n;
     4 void test(int row, int ld, int rd) {
     5     if (row == upperlim) {
     6         if (cnt < 3) {
     7             for (int j = 0; j < n; j++)
     8                 ans[cnt][j] = a[j]; //找到一个解,记录路径
     9             cnt++;
    10         } sum++;
    11         return ;
    12     }
    13     int pos = upperlim & ~(row | ld | rd); // 当前行的状况
    14     while (pos) {
    15         int bit = pos & (-pos); //取右边第一个1(详见树状数组)
    16         int p = bit, m = 0;
    17         while (p)  { p >>= 1; m++;}  //取其位置
    18         pos -= bit;  //搜索下一个位置
    19         a[c++] = m;  //记录路径
    20         test(row | bit, (ld | bit) << 1, (rd | bit) >> 1); 
    21         a[--c] = 0; //遍历完毕,删除该点
    22     }
    23 }
    24 int main() {
    25     scanf("%d", &n);
    26     upperlim = (1 << n) - 1;
    27     test(0, 0, 0);
    28     //printf("%d", cnt);
    29     for (int i = 0 ;i < cnt; i++){
    30         for (int j = 0; j < n; j++)
    31             printf("%d ", ans[i][j]); 
    32         puts("");
    33     }
    34     printf("%d", sum);
    35     return 0;
    36 } 
  • 相关阅读:
    Python3.6全栈开发实例[022]
    Python3.6全栈开发实例[021]
    Python3.6全栈开发实例[020]
    Python3.6全栈开发实例[019]
    Python3.6全栈开发实例[018]
    单选按钮QRadioButton
    QToolButton按钮
    文本编辑框QTextEdit
    信号-事件汇总
    QMessageBox消息框
  • 原文地址:https://www.cnblogs.com/cminus/p/7210317.html
Copyright © 2011-2022 走看看