Source:
Description:
The "eight queens puzzle" is the problem of placing eight chess queens on an 8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general N queens problem of placing N non-attacking queens on an N×N chessboard. (From Wikipedia - "Eight queens puzzle".)
Here you are NOT asked to solve the puzzles. Instead, you are supposed to judge whether or not a given configuration of the chessboard is a solution. To simplify the representation of a chessboard, let us assume that no two queens will be placed in the same column. Then a configuration can be represented by a simple integer sequence (, where Qi is the row number of the queen in the i-th column. For example, Figure 1 can be represented by (4, 6, 8, 2, 7, 1, 3, 5) and it is indeed a solution to the 8 queens puzzle; while Figure 2 can be represented by (4, 6, 7, 2, 8, 1, 9, 5, 3) and is NOT a 9 queens' solution.
Figure 1 Figure 2
Input Specification:
Each input file contains several test cases. The first line gives an integer K (1). Then Klines follow, each gives a configuration in the format "N Q1 Q2 ... QN", where 4 and it is guaranteed that 1 for all ,. The numbers are separated by spaces.
Output Specification:
For each configuration, if it is a solution to the N queens problem, print
YES
in a line; orNO
if not.
Sample Input:
48 4 6 8 2 7 1 3 59 4 6 7 2 8 1 9 5 36 1 5 2 6 4 35 1 3 5 2 4
Sample Output:
YESNONOYES
Keys:
- 简单模拟
Attention:
- 给出的N个皇后可能在同一行
Code:
1 /* 2 Data: 2019-05-25 10:24:05 3 Problem: PAT_A1128#N Queens Puzzle 4 AC: 18:04 5 6 题目大意: 7 判断给定的序列是否为N皇后问题的解 8 输入: 9 第一行给出:测试数K<=200;10 接下来K行,问题规模N<=1e3,N个数11 输出:12 Yes or No13 */14 15 #include16 #include 17 using namespace std;18 const int M=1e3+10;19 20 int main()21 {22 #ifdef ONLINE_JUDGE23 #else24 freopen("Test.txt", "r", stdin);25 #endif26 27 int n,m;28 scanf("%d", &m);29 while(m--)30 {31 scanf("%d", &n);32 int q[M],ans=1;33 for(int i=1; i<=n; i++)34 scanf("%d", &q[i]);35 for(int i=1; i<=n; i++)36 {37 for(int j=i+1; j<=n; j++)38 if(abs(j-i)==abs(q[j]-q[i]) || q[j]==q[i]){39 ans=0;break;40 }41 if(ans==0)42 break;43 }44 if(ans) printf("YES\n");45 else printf("NO\n");46 }47 48 return 0;49 }