题目
The “eight queens puzzle” is the problem of placing eight chess queens on an 8 × 8 8\times8 8×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 N N queens problem of placing N N N non-attacking queens on an N × N N\times N 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 ( Q 1 , Q 2 , ⋯ , Q N ) (Q_1,Q_2,⋯,Q_N) (Q1,Q2,⋯,QN), where Q i Q_i Qi is the row number of the queen in the i i 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.
:::hljs-center
Figure 1 | Figure 2 |
:::
Input Specification:
Each input file contains several test cases. The first line gives an integer K ( 1 < K ≤ 200 ) K(1\lt K\le200) K(1<K≤200). Then K K K lines follow, each gives a configuration in the format “ N Q 1 Q 2 . . . Q N N Q_1 Q_2...Q_N NQ1Q2...QN”, where 4 ≤ N ≤ 1000 4\le N\le1000 4≤N≤1000 and it is guaranteed that 1 ≤ Q i ≤ N 1\le Q_i\le N 1≤Qi≤N for all i = 1 , ⋯ , N i=1,⋯,N i=1,⋯,N. The numbers are separated by spaces.
Output Specification:
For each configuration, if it is a solution to the
N
N
N queens problem, print YES
in a line; or NO
if not.
题目大意
给出K个测试队列,每个队列有N个数据,第i个数字Qi就表示第i列第Qi行有一个女皇,判断棋盘上的女皇互相有没有威胁;而女皇之间无威胁的情况是女皇当前所在行与列以及斜对角线均没有其他女皇。
思路
八皇后问题需要同一行同一列以及同一正负对角线上都只能有一个皇后,所以题目需要判断同一行和对角线不能有多个皇后;
- 判断同一行,直接判断输入不重复即可;
- 判断正对角线,
d[i]-i
不能有重复; - 判断副对角线,
d[i]+i
不能有重复;
判断重复可以用set
实现;
代码
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
int main(){
int k, n;
set<int> s1, s2, s3;
scanf("%d", &k);
while(k--){
scanf("%d", &n);
for(int i=0, t; i<n; i++){
scanf("%d", &t);
s1.insert(t);
s2.insert(t-i);
s3.insert(t+i);
}
if(s1.size() < n || s2.size() < n || s3.size() < n)
printf("NO\n");
else
printf("YES\n");
s1.clear(), s2.clear(), s3.clear();
}
return 0;
}