#1128. N Queens Puzzle【模拟 + 排序】

原题链接

Problem Description:

The “eight queens puzzle” is the problem of placing eight chess queens on an 8 × 8 8\times 8 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, \cdots,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.
在这里插入图片描述在这里插入图片描述

Input Specification:

Each input file contains several test cases. The first line gives an integer K K K ( 1 < K ≤ 200 1<K\leq 200 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 \ldots\ Q_N N Q1 Q2 QN”, where 4 ≤ N ≤ 1000 4\leq N\leq 1000 4N1000 and it is guaranteed that 1 ≤ Q i ≤ N 1\leq Q_i \leq N 1QiN for all i = 1 , ⋯   , N i=1,\cdots,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.

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

Problem Analysis:

主要是横坐标和正副对角线需要标记一下,正对角线上所有点横纵坐标之差是相同的,副对角线上所有点横纵坐标之和是相同的,根据这个来标记所有点。

Code

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1010;

int n;
bool row[N], dg[2 * N], udg[2 * N];

int main()
{
    
    
    int T;
    cin >> T;
    
    while (T -- )
    {
    
    
        scanf("%d", &n);
        
        memset(row, 0, sizeof row);
        memset(dg, 0, sizeof dg);
        memset(udg, 0, sizeof udg);
        
        bool success = true;
        for (int y = 1; y <= n; y ++ )
        {
    
    
            int x;
            scanf("%d", &x);
            if (row[x] || dg[x + y] || udg[x - y + n]) success = false;
            row[x] = dg[x + y] = udg[x - y + n] = true;
        }
        
        if (!success) puts("NO");
        else puts("YES");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/geraltofrivia123/article/details/121273760