HDU 2553 N皇后问题
N皇后问题
Time Limit: 1000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 255364-bit integer IO format: %I64d Java class name: Main
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10
Source
解题:N皇后,位运算很厉害啊
1 #include <bits/stdc++.h> 2 using namespace std; 3 int uplimit,ret,n; 4 void dfs(int row,int ld,int rd){ 5 if(row == uplimit) ++ret; 6 else{ 7 int pos = uplimit & (~(row|ld|rd)); 8 while(pos){ 9 int p = pos&(-pos); 10 pos ^= p; 11 dfs(row|p,(ld|p)<<1,(rd|p)>>1); 12 } 13 } 14 } 15 int main(){ 16 while(scanf("%d",&n),n){ 17 uplimit = (1<<n)-1; 18 ret = 0; 19 dfs(0,0,0); 20 printf("%d\n",ret); 21 } 22 return 0; 23 }
夜空中最亮的星,照亮我前行