1. 程式人生 > 其它 >PAT (Advanced Level) Practice 1128 N Queens Puzzle (20 分) 凌宸1642

PAT (Advanced Level) Practice 1128 N Queens Puzzle (20 分) 凌宸1642

PAT (Advanced Level) Practice 1128 N Queens Puzzle (20 分) 凌宸1642

題目描述:

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 個皇后問題的一個例子。 (來自維基百科 - “八皇后之謎”。)

在這裡,您不需要解決難題。 相反,您應該判斷棋盤的給定配置是否是解決方案。 為了簡化棋盤的表示,讓我們假設不會在同一列中放置兩個皇后。 那麼一個配置可以用一個簡單的整數序列 (Q1 ,Q2 ,⋯,QN ) 來表示,其中 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

The Idea:

  • 考察的是什麼時候滿足 N-皇后 問題的解的情況,這裡題目中已經保證了不會出現在同一列,那麼只要不再出現在同一行,已經不出現在對角線上,即使滿足要求的解

The Codes:

#include<bits/stdc++.h>
using namespace std ;
int n , num[1010] , k;
bool deal(int n){
	for(int i = 0 ; i < n - 2 ; i ++){
		for(int j = i + 1 ; j < n ; j ++){
			if((abs(num[i] - num[j]) == abs(i - j)) || num[i] == num[j]) return false ;
		}
	}
	return true ;
}
int main(){
	cin >> k ;
	while(k --){
		cin >> n ;
		for(int i = 0 ; i < n ; i ++) cin >> num[i] ;
		if(deal(n)) cout << "YES" << endl ;
		else cout << "NO" << endl ;
	}
	return 0 ;
}