题意:给定一个棋盘,棋盘上有一个白皇后,和多个黑色的车,象,和皇后。问当前白皇后是否是将军。
思路 用四个数组来存白皇后所在的行列斜线上的棋子,然后对数组排序,二分查找找到皇后的位置,判断皇后在行列斜向上的前后两个棋子是不是能吃到她。时间复杂度 O(nlogn) ,实际上只要用8个变量来维护最近的棋子就行了,时间复杂度 O(n) 。
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdlib>
using namespace std;
struct node
{
int t;
int x, y;
node(int _t = 0, int _x = 0, int _y = 0) :t(_t), x(_x), y(_y){}
};
bool cmp(const node &x, const node &y)
{
if (x.x != y.x)return x.x < y.x;
return x.y < y.y;
}
int main()
{
int n;
scanf("%d", &n);
int qx, qy;
scanf("%d%d", &qx, &qy);
vector<node>c, h, xx, yy;
for (int i = 0; i < n; i++)
{
char s[2];
int x, y;
scanf("%s%d%d",s, &x, &y);
if (x == qx)h.push_back(node(s[0], x, y));
if (y == qy)c.push_back(node(s[0], x, y));
if (x + y == qx + qy)xx.push_back(node(s[0], x, y));
if (x - y == qx - qy)yy.push_back(node(s[0], x, y));
}
c.push_back(node(0, qx, qy));
h.push_back(node(0, qx, qy));
xx.push_back(node(0, qx, qy));
yy.push_back(node(0, qx, qy));
sort(c.begin(), c.end(), cmp);
sort(h.begin(), h.end(),cmp);
sort(xx.begin(), xx.end(), cmp);
sort(yy.begin(), yy.end(),cmp);
int flag = 1;
node qq = node(0, qx, qy);
int p1 = lower_bound(c.begin(), c.end(), qq,cmp) - c.begin();
int p2 = lower_bound(h.begin(), h.end(),qq,cmp) - h.begin();
int p3 = lower_bound(xx.begin(), xx.end(),qq,cmp) - xx.begin();
int p4 = lower_bound(yy.begin(), yy.end(),qq, cmp) - yy.begin();
if ((p1 != 0 && (c[p1 - 1].t == 'R' || c[p1 - 1].t == 'Q')) || (p1 != c.size() - 1 && (c[p1 + 1].t == 'R' || c[p1 + 1].t == 'Q')))flag = 0;
if ((p2 != 0 && (h[p2 - 1].t == 'R' || h[p2 - 1].t == 'Q')) || (p2 != h.size() - 1 && (h[p2 + 1].t == 'R' || h[p2 + 1].t == 'Q')))flag = 0;
if ((p3 != 0 && (xx[p3 - 1].t == 'B' || xx[p3 - 1].t == 'Q')) || (p3 != xx.size() - 1 && (xx[p3 + 1].t == 'B' || xx[p3 + 1].t == 'Q')))flag = 0;
if ((p4 != 0 && (yy[p4 - 1].t == 'B' || yy[p4 - 1].t == 'Q')) || (p4 != yy.size() - 1 && (yy[p4 + 1].t == 'B' || yy[p4 + 1].t == 'Q')))flag = 0;
puts(flag ? "NO" : "YES");
//getchar();
//getchar();
}