两种思路:
1. 用二维数组模拟一个棋盘,对每个皇后所在的行、对角线进行扫描,如果没有其它皇后,则输出YES,否则输出NO。
#include<cstdio>
#include<algorithm>
#include<vector>
#include<unordered_set>
using namespace std;
bool board[1001][1001];
vector<int> input[200];
int main() {
int k;
scanf("%d", &k);
for (int i = 0;i < k;i++) {
int n;
scanf("%d", &n);
input[i].resize(n);
for (int j = 0;j < n;j++) {
scanf("%d", &input[i][j]);
}
}
for (int i = 0;i < k;i++) {
fill(board[0], board[0] + 1001 * 1001, false);
bool isSolution = true;
int n = input[i].size();
unordered_set<int> rowOccupied;
for (int j = 0;j < n;j++) {
if (rowOccupied.count(input[i][j]) != 0) {
isSolution = false;
goto outer;
}
rowOccupied.insert(input[i][j]);
int row = input[i][j], column = j + 1;
while (row >= 1 && column >= 1) {
if (board[row][column]) {
isSolution = false;
goto outer;
}
row--;
column--;
}
row = input[i][j] - 1, column = j + 1 + 1; //右上
while (row >= 1 && column <= n) {
if (board[row][column]) {
isSolution = false;
goto outer;
}
row--;
column++;
}
row = input[i][j] + 1, column = j + 1 - 1; //左下
while (row <= n && column >= 1) {
if (board[row][column]) {
isSolution = false;
goto outer;
}
row++;
column--;
}
row = input[i][j] + 1, column = j + 1 + 1; //右下
while (row <= n && column <= n) {
if (board[row][column]) {
isSolution = false;
goto outer;
}
row++;
column++;
}
board[input[i][j]][j + 1] = true;
}
outer:
if (isSolution) {
printf("YES\n");
}
else printf("NO\n");
}
}
2. 对每两个皇后,计算它们所成直线的斜率,如果斜率为1,则说明它们在同一对角线上。
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
vector<int> input;
int main() {
int k;
scanf("%d", &k);
for (int i = 0;i < k;i++) {
int n;
scanf("%d", &n);
input.resize(n);
for (int j = 0;j < n;j++) {
scanf("%d", &input[j]);
}
bool isSolution = true;
for (int j = 0;j < input.size() - 1;j++) {
for (int m = j + 1;m < input.size();m++) {
if (abs(input[j] - input[m]) == abs(j - m) || input[j] == input[m]) { //注意取绝对值
isSolution = false;
goto outer;
}
}
}
outer:
if (isSolution)
printf("YES\n");
else printf("NO\n");
}
}