CodeForces 621B B. Wet Shark and Bishops【数学+思路】

来源:互联网 发布:js position absolute 编辑:程序博客网 时间:2024/05/16 10:52

B. Wet Shark and Bishops

Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Submit Status Practice CodeForces 621B

Description

Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.

Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.

Input

The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops.

Each of next n lines contains two space separated integers xi and yi (1 ≤ xi, yi ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.

Output

Output one integer — the number of pairs of bishops which attack each other.

Sample Input

Input
51 11 53 35 15 5
Output
6
Input
31 12 33 5
Output
0

Hint

In the first sample following pairs of bishops attack each other: (1, 3)(1, 5)(2, 3)(2, 4)(3, 4) and (3, 5). Pairs (1, 2)(1, 4)(2, 5)and (4, 5) do not attack each other because they do not share the same diagonal.


题意:

给出1000*1000 的矩阵,上面有很多个物品,当两个物品在同一条对角线上时,能相互攻击,给出n个物品的坐标,问能相互攻击的对数有多少


题解:

数据范围比较大,如果直接进行暴力循环求解肯定会超时,仔细观察矩阵的性质发现

1,如果两个元素在同一条平行于主对角线的对角线上,那么他们的行和列的差值相等,

2,如果两个元素在同一条平行于副对角线的对角线上,那么他们的行和列的和相等


然后就是分别统计,并且找出所有在同一对角线上元素个数,每种选两个,累乘既得到答案。


#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int x[200005],y[200005];typedef long long ll;ll num(int tp[],int n){ll ans=0;int i=0;while(i<n){int l=lower_bound(tp,tp+n,tp[i])-tp,r=upper_bound(tp,tp+n,tp[i])-tp;ans+=(r-l)*(r-l-1)/2;i=r;}return ans;}int main(){int n;while(~scanf("%d",&n)){int a,b;for(int i=0;i<n;++i){scanf("%d%d",&a,&b);x[i]=a-b;y[i]=a+b;}sort(x,x+n);sort(y,y+n);ll ans=0;ans=ans+num(y,n)+num(x,n);printf("%lld\n",ans);}return 0;}




0 0
原创粉丝点击