題目鏈接
題意:給出n個點的座標,求曼哈頓距離不小於d的點對數。
我們將座標①變換爲②,那麼①的曼哈頓距離等於②的切比雪夫距離。
切比雪夫距離
那麼對於點 來說,不合法的點就變成了以 點爲中心,邊長爲 的正方形內點的個數(不包括邊上的)
上述所說的所有的正方形當然會有重合的部分,所以我們可以選擇只統計每個正方形的左半邊。
我們用樹狀數組來維護某橫座標區間內縱座標的個數,枚舉橫座標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;
}