【p1219-八皇后】解题记录

题目链接

题目本身没什么好说的,只是要用位压来加速,否则最后一个点会超时。

#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;
}
    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/Zhaosiyii/article/details/68954129
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞