1128 N Queens Puzzle (20 分)
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
忽略了重要问题的代码
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int K;
cin >> K; //共K组待评判数据
while (K--) {
int N, Standard, Next, flag = 1; //皇后数量 标准数 对比数 评判结果
cin >> N >> Standard; //得到初始标准数
while (--N) { //注意已经有初始皇后 故采用--N
cin >> Next;
if (Standard == Next || abs(Standard - Next) == 1) { flag = 0; } //标记求解失败 但仍扫完其他皇后
else Standard = Next; //标准右移
}
if (flag) cout << "YES" << endl; //求解成功
else cout << "NO" << endl; //求解失败
}
return 0;
} //此代码忽略了重要问题--->任意两个皇后都要满足题干条件
AC代码
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int K;
cin >> K; //共K组待评判数据
while (K--) {
int N;
cin >> N; //皇后个数
int *Qs = new int[N+1]; //用于存储各皇后
for (int i = 1; i <= N; i++) cin >> Qs[i];
int flag = 1; //求解结果
for (int i = 2; i <= N; i ++) {
for (int j = 1; j < i; j++)
if (abs(Qs[i] - Qs[j]) == (i - j) || Qs[i] == Qs[j]) { flag = 0; break; }
if (!flag) break;
}
if (flag) cout << "YES" << endl;
else cout << "NO" << endl;
delete[] Qs; //释放动态数组
}
return 0;
}