N皇后 (位运算)

二进制log2(t)+1 便是位数

#include<iostream>
#include<cmath>
#include<cstdio> 
#include<cstring>
#include<algorithm>
#include<queue> 
using namespace std;
int n;
int p;
int s=0;
 int sol[999];
int ans=0;
int log2(int a)//log
{
    switch (a)
    {
    case 1:
        return 1;
    case 2:
        return 2;
    case 4:
        return 3;
    case 8:
        return 4;
    case 16:
        return 5;
    case 32:
        return 6;
    case 64:
        return 7;
    case 128:
        return 8;
    case 256:
        return 9;
    case 512:
        return 10;
    case 1024:
        return 11;
    case 2048:
        return 12;
    case 4096:
        return 13;
    }
}
void print()
{ 
    for(int i=1;i<=n;i++)
    {
        printf("%d ",log2(sol[i]));
    }
    printf("
");
}
void dfs(int r,int rl,int ll)
{
    if(r==p) 
    {
    ans++;  
    if(ans<=3)
    print();
    return;
    }
    int pos=p&~(r|rl|ll);  
    while(pos!=0)
    {
        int t=pos&(-pos);
        pos-=t;

        sol[++s]=t; 
        dfs(r|t,(rl|t)<<1,(ll|t)>>1);
        --s;
    }
}
int main()
{
    scanf("%d",&n);
    p=(1<<n)-1;
    dfs(0,0,0);
    printf("%d",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/wspl98765/p/6819897.html