1128 N Queens Puzzle (20分)

题目

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 1Figure 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<K200). 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 4N1000 and it is guaranteed that 1 ≤ Q i ≤ N 1\le Q_i\le N 1QiN 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行有一个女皇,判断棋盘上的女皇互相有没有威胁;而女皇之间无威胁的情况是女皇当前所在行与列以及斜对角线均没有其他女皇。

思路

八皇后问题需要同一行同一列以及同一正负对角线上都只能有一个皇后,所以题目需要判断同一行和对角线不能有多个皇后;

  1. 判断同一行,直接判断输入不重复即可;
  2. 判断正对角线,d[i]-i不能有重复;
  3. 判断副对角线,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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值