#1497 : Queen Attack(类似八皇后经典问题的判断)

描述

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值