题目链接
现在,我们来认识一下,曼哈顿距离转换成切比雪夫距离有什么好处?——更加简单的处理“曼哈顿距离大于等于D的点对数目”。
我们现在的曼哈顿距离假设为,那么,我们假设有这样的切比雪夫距离
连立两个不等式,得到,。
好了,我们将原来的问题转化为了求切比雪夫距离大于等于D的点对数,这样问题就简单了,我们可以利用单调队列+树状数组等数组结构来维护了。
因为只要保证一维大于等于D,就是点对是合法的。
所以我们首先对x升序,于是,用单调队列O(N)的来维护,然后就是查询y了,树状数组查询,基本操作了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define eps 1e-8
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, D, L, tx, ty, top, tail, Lsan[maxN], _UP;
struct node
{
int x, y;
node(int a=0, int b=0):x(a), y(b) {}
void In()
{
scanf("%d%d", &tx, &ty);
x = tx + ty; y = tx - ty;
}
friend bool operator < (node e1, node e2) { return e1.x < e2.x; }
} a[maxN], que[maxN];
struct BIT_Tree
{
int tree[maxN], all = 0;
inline void update(int x, int val)
{
all += val;
while(x <= N)
{
tree[x] += val;
x += lowbit(x);
}
}
inline int query(int x)
{
int sum = 0;
while(x)
{
sum += tree[x];
x -= lowbit(x);
}
return sum;
}
} b;
int main()
{
top = tail = 0;
scanf("%d%d%d", &N, &D, &L);
for(int i=1; i<=N; i++) { a[i].In(); Lsan[i] = a[i].y; }
sort(a + 1, a + N + 1);
sort(Lsan + 1, Lsan + N + 1);
_UP = (int)(unique(Lsan + 1, Lsan + N + 1) - Lsan - 1);
ll ans = 0;
for(int i=1, id; i<=N; i++)
{
while(top < tail && que[top].x <= a[i].x - D)
{
id = (int)(lower_bound(Lsan + 1, Lsan + _UP + 1, que[top].y) - Lsan);
b.update(id, -1);
top++;
}
ans += top;
id = (int)(upper_bound(Lsan + 1, Lsan + _UP + 1, a[i].y - D) - Lsan - 1);
ans += b.query(id);
id = (int)(lower_bound(Lsan + 1, Lsan + _UP + 1, a[i].y + D) - Lsan - 1);
ans += tail - top - b.query(id);
que[tail++] = a[i];
id = (int)(lower_bound(Lsan + 1, Lsan + _UP + 1, a[i].y) - Lsan);
b.update(id, 1);
}
printf("%lld\n", ans);
return 0;
}