题目链接
题意:给出n个点的坐标,求曼哈顿距离不小于d的点对数。
我们将坐标① ( x , y ) (x,y) (x,y)变换为② ( x + y , x − y ) (x + y, x - y) (x+y,x−y),那么①的曼哈顿距离等于②的切比雪夫距离。
切比雪夫距离 d i s = m a x ( ∣ x 2 − x 1 ∣ , ∣ y 2 − y 1 ∣ ) dis=max(|x_2-x_1|, |y_2-y_1|) dis=max(∣x2−x1∣,∣y2−y1∣)
那么对于点
i
i
i 来说,不合法的点就变成了以
i
i
i 点为中心,边长为
2
d
\ 2d
2d 的正方形内点的个数(不包括边上的)
上述所说的所有的正方形当然会有重合的部分,所以我们可以选择只统计每个正方形的左半边。
我们用树状数组来维护某横坐标区间 ( x − d , x ] (x - d, x] (x−d,x]内纵坐标的个数,枚举横坐标x即可。
#include <iostream>
#include <cstdio>
#include <algorithm>
#define lowbit(x) x & (-x)
#define INF 0x3f3f3f3f3f3f
using namespace std;
typedef long long ll;
int read()
{
int x = 0, f = 1; char c = getchar();
while (c < '0' || c > '9') { if (c == '-') f = -f; c = getchar(); }
while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
return x * f;
}
const int maxN = 200005;
struct node{
int x, y;
node() {}
node(int a, int b): x(a), y(b){}
friend bool operator < (node n1, node n2) { return n1.x < n2.x; }
}mp[maxN];
int tree[maxN];
int n, d, L;
int up;
void Insert(int pos, int val)
{
while(pos <= up)
{
tree[pos] += val;
pos += lowbit(pos);
}
}
int query(int pos)
{
int ans = 0;
while(pos > 0)
{
ans += tree[pos];
pos -= lowbit(pos);
}
return ans;
}
int main()
{
n = read(); d = read(); L = read();
up = 4 * L + 1;
for(int i = 1; i <= n; ++ i )
{
int xx = read(), yy = read();
mp[i].x = xx + yy + 2 * L + 1, mp[i].y = xx - yy + 2 * L + 1;
}
sort(mp + 1, mp + 1 + n);
int l = 1;
ll ans = (ll)n * ll(n - 1) / 2ll;
for(int i = 1; i <= n; ++ i )
{
while(l < i && mp[l].x + d <= mp[i].x)
Insert(mp[l].y, -1), ++ l;
ans -= ll(query(min(mp[i].y + d - 1, up)) - query(mp[i].y - d));
Insert(mp[i].y, 1);
}
printf("%lld\n", ans);
return 0;
}