基本N皇后问题(位运算优化)

#include 
#include 
#include 
using namespace std;
int uplimit;
int sum = 0;
int n;
vector<int> res;
void doans(int r, int ld, int rd)
{
    if (r != uplimit)
    {
        int pos=uplimit&~(r | ld | rd);
        while (pos)
        {
            int p = pos&-pos;
            pos -= p;
            res.push_back(n-log2(p));
            doans(r | p, (ld | p) << 1, (rd | p) >> 1);
            res.pop_back();
        }
    }
    else
    {
        for (int i = 0; i < res.size(); ++i)
            cout << res[i] << " ";
        cout << endl;
        sum++;
    }
}
int main()
{
    while (cin >> n)
    {
        if (n == 0)
            break;
        sum = 0;
        res.clear();
        uplimit = (1 << n) - 1;
        doans(0, 0, 0);
        cout << sum << endl;
    }
    return 0;
}

你可能感兴趣的:(基本N皇后问题(位运算优化))