拉普兰德的愿望【切比雪夫距离+树状数组】

题目链接

题意:给出n个点的坐标,求曼哈顿距离不小于d的点对数。


我们将坐标① ( x , y ) (x,y) (x,y)变换为② ( x + y , x − y ) (x + y, x - y) (x+y,xy),那么①的曼哈顿距离等于②的切比雪夫距离。

切比雪夫距离 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(x2x1,y2y1)

那么对于点 i i i 来说,不合法的点就变成了以 i i i 点为中心,边长为   2 d \ 2d  2d 的正方形内点的个数(不包括边上的)
上述所说的所有的正方形当然会有重合的部分,所以我们可以选择只统计每个正方形的左半边。

我们用树状数组来维护某横坐标区间 ( x − d , x ] (x - d, x] (xd,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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值