N皇后超加速

位元運算
可以,這很星爆


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int n,limit,cnt;
int x[21],k=1;
//行,左對角線,右對角線
void DFS(int row,int left,int right)
{
    if(row!=limit)
    {
        int pos=limit&~(row|left|right);
        while(pos)
        {
            //找到的可以放皇后的位置
            int p=pos&-pos;// pos & (~pos+1); aka lowbit
            pos&=pos-1;
            DFS(row|p,(left|p)<<1,(right|p)>>1);
        }
    }
    else
    {
        cnt++;
    }
}

int main()
{
    while(cin>>n)
    {
        cnt=0;
        limit=(1<<n)-1;
        DFS(0,0,0);
        cout<<cnt<<endl;
    }
}

參考文章:N皇后問題(各種優化)