一、题目描述
Input Specification:
Output Specification:
For each configuration, if it is a solution to the 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
二、解题思路
给出每一列的棋子所在的行数,利用一个二层循环判断有没有两个棋子在同一行或同一条对角线上,如果在,输出NO并跳出循环即可,否则输出YES。
三、AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int main()
{
int N;
scanf("%d", &N);
for(int i=0; i<N; i++)
{
int K;
scanf("%d", &K); //输入元素个数
int a[K+1];
bool flag = true; //假设序列是对应K皇后问题的解
for(int j=1; j<=K; j++)
scanf("%d", &a[j]);
for(int j=1; j<K; j++)
{
for(int k=j+1; k<=K; k++)
{
if(a[j] == a[k] || abs(a[j] - a[k]) == k-j) //判断两棋子是否在同一行以及是否在对角线上
{
flag = false;
printf("NO\n");
break;
}
}
if(!flag) break;
}
if(flag) printf("YES\n");
}
return 0;
}