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
就是皇后问题判重,判断行重复 对角线重复就好,我写代码时候写多了个判断列重复,题目已经很明确说了列不会重复。注意的点有
- 题目给的位置标示好难受,从左下角数,我还是变成了左上角开始的数组
- 然后关于对角重复判断,直接行标-列标就能得到一个 对角元素都一样的值,比如从主对角线的元素 行标减列标都是0了
- 判重最快还是开个N个元素的数组,默认为0, 有元素了就是1,没有就是0
- 对于行标减去列标 进行对角线判重的话,使用#include <unordered_set> 可以
代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
using namespace std;
int main()
{
int K;
cin>>K;
for(int k=0; k<K; k++)
{
unordered_set<int> sett;
int sign=1;
int N;
cin>>N;
int setRow[N+1]={0};
int setCol[N+1]={0};
int sn[N+1][N+1]= {0};
for(int n=1; n<=N; n++)
{
//n是从左下角数的 第几列
int m;
cin>>m;
//m是第几行
//这表示好难受,
int trueRow=N+1-m;
int trueCol=N+1-n;
sn[trueRow][trueCol]=1;
int get=trueRow-trueCol;
if(sett.find(trueRow-trueCol)==sett.end())
sett.insert(trueRow-trueCol);
else
{
sign=0;
}
if(setRow[trueRow]==0)
setRow[trueRow]=1;
else
{
sign=0;
}
if(setCol[trueCol]==0)
setCol[trueCol]=1;
else
{
sign=0;
}
}
if(sign==1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}