-
题目描述:
-
会下国际象棋的人都很清楚:皇后可以在横、竖、斜线上不限步数地吃掉其他棋子。如何将8个皇后放在棋盘上(有8 * 8个方格),使它们谁也不能被吃掉!这就是著名的八皇后问题。
对于某个满足要求的8皇后的摆放方法,定义一个皇后串a与之对应,即a=b1b2...b8,其中bi为相应摆法中第i行皇后所处的列数。已经知道8皇后问题一共有92组解(即92个不同的皇后串)。
给出一个数b,要求输出第b个串。串的比较是这样的:皇后串x置于皇后串y之前,当且仅当将x视为整数时比y小。
-
输入:
-
第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数b(1 <= b <= 92)
-
输出:
-
输出有n行,每行输出对应一个输入。输出应是一个正整数,是对应于b的皇后串。
-
样例输入:
-
2 1 92
-
样例输出:
-
15863724 84136275
-
-
#include <stdio.h> #include <iostream> #include <cstring> #include <string> #include <vector> using namespace std; vector<string> res; char ans[10]; int cnt; bool x_y[15]; //斜对角线1 bool x_y1[16]; //斜对角线2 const int OFFSET = 7; bool col[9]; //列 void DFS(int i) { if(cnt == 8) { ans[cnt] = '\0'; string a = ans; res.push_back(a); return; } else { for(int j = 1; j <= 8; j++) { if(col[j] == false && x_y[j-i+OFFSET] == false && x_y1[i+j-2] == false) { ans[cnt] = j + '0'; cnt++; col[j] = true; x_y[j-i+OFFSET] = true; x_y1[i+j-2] = true; i++; DFS(i); cnt--; i--; col[j] = false; x_y[j-i+OFFSET] = false; x_y1[i+j-2] = false; } } } } int main() { int n; scanf("%d",&n); int i; cnt = 0; for(i = 0; i < 15; i++) { x_y[i] = false; x_y1[i] = false; } for(i = 1; i <= 8; i++) col[i] = false; i = 1; DFS(i); while(n--) { int b; scanf("%d",&b); cout << res[b-1] << endl; } }