HDU2553 n皇后问题

这么一道经典的题就不用多解释题意了,只是这里答案要先存下来

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstring>
 5 #include <cmath>
 6 #include <sstream>
 7 #include <algorithm>
 8 #include <set>
 9 #include <map>
10 #include <vector>
11 #include <queue>
12 #include <iomanip>
13 
14 using namespace std;
15 
16 typedef long long LL;
17 const int INF = 0x3f3f3f3f;
18 const int MAXN = 5005;
19 const int MOD = 1e9 + 7;
20 
21 #define MemN(x) memset(x, -1, sizeof(x))
22 #define Mem0(x) memset(x, 0, sizeof(x))
23 #define MemM(x) memset(x, 0x3f, sizeof(x))
24 
25 //p[i] = t, 第 i 行第 t 列
26 int p[15], ans[15], num;
27 //横坐标的差与纵坐标的差相同即为处于对角线
28 bool check(int r, int c)
29 {
30     for(int i = 1;i < r;++i)
31         if(p[i] == c || abs(p[i] - c) == abs(i - r))
32             return false;
33     return true;
34 }
35 
36 void dfs(int Index, int n)
37 {
38     if(Index > n)
39     {
40         num++;
41         return ;
42     }
43     for(int i = 1;i <= n;++i)
44     {
45         if(check(Index, i))
46         {
47             p[Index] = i;
48             dfs(Index + 1, n);
49             p[Index] = 0;
50         }
51     }
52 }
53 
54 void Init()
55 {
56     for(int i = 1;i < 11;++i)
57     {
58         num = 0;
59         Mem0(p);
60         dfs(1, i);
61         ans[i] = num;
62     }
63 }
64 
65 int main()
66 {
67     Init();
68     int n;
69     while(cin >> n && n)
70         cout << ans[n] << endl;
71     return 0;
72 }

不过看到一篇有意思的博客 

关于八皇后的 n 种解法 :https://www.cnblogs.com/xinghuan/p/6061824.htm 

这里给出里面关于位运算解法:这里详解 https://blog.csdn.net/Dora_Bin/article/details/52733832?locationNum=7

要点:p & (-p)能取二进制 p 最低位的 1

照着码

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstring>
 5 #include <cmath>
 6 #include <sstream>
 7 #include <algorithm>
 8 #include <set>
 9 #include <map>
10 #include <vector>
11 #include <queue>
12 #include <iomanip>
13 
14 using namespace std;
15 
16 typedef long long LL;
17 const int INF = 0x3f3f3f3f;
18 const int MAXN = 5005;
19 const int MOD = 1e9 + 7;
20 
21 #define MemN(x) memset(x, -1, sizeof(x))
22 #define Mem0(x) memset(x, 0, sizeof(x))
23 #define MemM(x) memset(x, 0x3f, sizeof(x))
24 
25 int ans[15];
26 int num;
27 void dfs(int Index, int l, int r, int n)
28 {
29     if(Index == n)
30     {
31         num++;
32         return ;
33     }
34     int pos = n & (~(Index | l | r));
35     while(pos)
36     {
37         int p = pos & (-pos);
38         pos -= p;
39         dfs(Index | p, (l | p) << 1, (r | p) >> 1, n);
40     }
41 }
42 
43 void Init()
44 {
45     for(int i = 1;i < 11;++i)
46     {
47         num = 0;
48         dfs(0, 0, 0, (1 << i) - 1);
49         ans[i] = num;
50     }
51 }
52 
53 int main()
54 {
55     Init();
56     int n;
57     while(cin >> n && n)
58         cout << ans[n] << endl;
59     return 0;
60 }
现在所有的不幸都是以前不努力造成的。。。
原文地址:https://www.cnblogs.com/shuizhidao/p/9341446.html