题目本身没什么好说的,只是要用位压来加速,否则最后一个点会超时。
#include <cstdio>
#include <cstdlib>
using namespace std;
int size;
const int MAX_SIZE= 100;
long long filled_column,
filled_main_diagonal,
filled_vice_diagonal;
int answer[MAX_SIZE], cnt_ans=0;
void dfs(int line){
if(line>size){
++cnt_ans;
if(cnt_ans<=3){
for(int i=1; i<=size; ++i){
printf("%d ", answer[i]);
}
putchar('\n');
}
return;
}
for(int col=1; col<=size; ++col){
if(filled_column&(1LL<<col)
|filled_main_diagonal&(1LL<<(col+line))
|filled_vice_diagonal&(1LL<<(line-col+size))) continue;
filled_column|=(1LL<<col);
filled_main_diagonal|=(1LL<<(col+line));
filled_vice_diagonal|=(1LL<<(line-col+size));
answer[line]= col;
dfs(line+1LL);
filled_column&= ~(1LL<<col);
filled_main_diagonal&= ~(1LL<<(col+line));
filled_vice_diagonal&= ~(1LL<<(line-col+size));
}
}
int main(){
scanf("%d", &size);
dfs(1);
printf("%d\n", cnt_ans);
return 0;
}