题目描述
The “eight queens puzzle” is the problem of placing eight chess queens on an 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 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 (Q1 ,Q2 ,⋯,QN), 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.
翻译:“八皇后问题”,是将八个国际象棋女王在一个8×8棋盘,没有两个皇后威胁对方。因此,解决方案要求没有两个皇后在相同的行、列或对角线。八皇后问题是一个更一般的N皇后问题——给一个N×N N非攻击性皇后区棋盘——的一种示例。(摘自维基百科——“八皇后谜题”。)
这里不要求你解谜。相反,您应该判断棋盘的给定配置是否是一个解决方案。为了简化棋盘的表示,我们假设没有两个皇后放在同一列中。然后棋盘可以表示为一个简单的整数序列(Q 1,Q2,⋯,Q N),Qi是第i列的女王的行号。例如,图1可以表示为(4、6、8、2、7、1、3、5),它确实是8皇后问题的解;而图2可以表示为(4、6、7、2、8、1、9、5、3),它不是9皇后的解。
Input Specification:
Each input file contains several test cases. The first line gives an integer K (1<K≤200). Then K lines follow, each gives a configuration in the format "N Q1 Q2 … QN ", where 4≤N≤1000 and it is guaranteed that 1≤Qi≤N for all i=1,⋯,N. The numbers are separated by spaces.
翻译:每个输入文件包含几个测试数据。第一行给出一个正整数K (1<K≤200)。接下来的K行,每行按照"N Q1 Q2 … QN "的格式给出一个解决方案,4≤N≤1000,数据保证1≤Qi≤N,i=1,…,N。数字之间用空格隔开。
Output Specification:
For each configuration, if it is a solution to the N queens problem, print YES in a line; or NO if not.
翻译:对于每个解决方案,如果它是N皇后问题的解,则输出一行YES,否则输出NO。
Sample Input:
4
8 4 6 8 2 7 1 3 5
9 4 6 7 2 8 1 9 5 3
6 1 5 2 6 4 3
5 1 3 5 2 4
Sample Output:
YES
NO
NO
YES
解题思路
说实话,给的图没看懂。还好知道要判断什么。由于只是判断是否为N皇后,不需要用到回溯。这道题的考点在于时间。如果对每个皇后循环判断用Q[i]-i==0||abs(Q[i]-Q[j])==i-j;
是可以过的,但是时间大约为170ms-190ms。可以考虑用两个bool数组来保存对角线和行是否访问过,用时能缩减到40ms。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
#define bug puts("Hello\n")
using namespace std;
int K,N;
bool Diag[2010],Row[1010];
int main(){
scanf("%d",&K);
for(int k=0;k<K;k++){
memset(Diag,0,sizeof(Diag));
memset(Row,0,sizeof(Row));
scanf("%d",&N);
bool flag=false;
int tmp;
for(int i=1;i<=N;i++){
scanf("%d",&tmp);
if(Row[tmp]||Diag[tmp-i+N])flag=true;
if(!Row[tmp])Row[tmp]=true;
if(!Diag[tmp-i+N])Diag[tmp-i+N]=true;
}
if(flag)printf("NO\n");
else printf("YES\n");
}
return 0;
}