描述
There are N queens in an infinite chessboard. We say two queens may attack each other if they are in the same vertical line, horizontal line or diagonal line even if there are other queens sitting between them.
Now given the positions of the queens, find out how many pairs may attack each other?
输入
The first line contains an integer N.
Then N lines follow. Each line contains 2 integers Ri and Ci indicating there is a queen in the Ri-th row and Ci-th column.
No two queens share the same position.
For 80% of the data, 1 <= N <= 1000
For 100% of the data, 1 <= N <= 100000, 0 <= Ri, Ci <= 1000000000
输出
One integer, the number of pairs may attack each other.
5 1 1 2 2 3 3 1 3 3 1样例输出
10
前次一个网络赛,遇到了一个n皇后问题,怕TLE,没敢写,后来发现,自己的想法是正确的,这里又遇到了一个类似的问题,稍简单些,用那个思路直接遍历一遍暴力,中间用四个数组判断八个方向的情况(类似八皇后的判断法),原来主要怕排序的时候炸,因为原来的数据量很大。
但是这里还是因为数组太大炸了,因为数据量还可以,但是数据的大小太大了,本来可以离散化,但是这种二维的题,还有很多限制条件,牵一发而动全身,后来用map来代替四个数组判断方向,这样就能满足离散化的要求,既不用离散化,数组的空间也不大。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MA=110000;
struct poin
{
int x,y;
}G[MA];
int cmp(poin a,poin b)
{
if(a.y<b.y)return 1;
else if(a.y==b.y)
{
if(a.x<b.x)return 1;
}
return 0;
}
map<int,int>X;
map<int,int>Y;
map<int,int>SH;
map<int,int>NI;
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
scanf("%d%d",&G[i].x,&G[i].y);
}
sort(G,G+n,cmp);
int sum=0;
for(int i=0;i<n;i++)
{
int u=G[i].x,v=G[i].y;
if(X[u])sum+=X[u];
if(Y[v])sum+=Y[v];
if(NI[u+v])sum+=NI[u+v];
if(SH[u-v+n])sum+=SH[u-v+n];
X[u]++;
Y[v]++;
NI[u+v]++;
SH[u-v+n]++;
}
printf("%d\n",sum);
return 0;
}