luogu1219 [八皇后] 搜索

来源:互联网 发布:nginx location root 编辑:程序博客网 时间:2024/05/21 14:43

把每行选的数作为状态,按字典序的顺序搜索。

#include <cmath>#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>using namespace std;const int N = 103 + 5 ;int li [N] , zu [N] , yo [N] , a [N] ;int n , ans;void dfs ( int h ){    for ( int i = 1 ; i <= n ; ++ i ) {        if ( ( !li [i] ) && (! zu [ h-i+20 ] ) && (! yo [h+i] ) ){            li [i] = zu [ h-i+20 ] = yo [h+i] = 1 ;            a [h] = i ;            if ( h == n ){                ans ++ ;                if ( ans <= 3 ){                    for ( int j = 1 ; j <= n ; ++ j )                         printf ( "%d " , a [j] ) ;                    puts("");                 }            }else {                dfs ( h+1 ) ;            }            li [i] = zu [ h-i+20 ] = yo [h+i] = 0 ;        }    }}int main () {    scanf ( "%d" , &n ) ;    ans = 0 ;    dfs (1);    printf ( "%d" , ans ) ;    return 0 ;}
原创粉丝点击