拉普蘭德的願望【切比雪夫距離+樹狀數組】

題目鏈接

題意:給出n個點的座標,求曼哈頓距離不小於d的點對數。


我們將座標①(x,y)(x,y)變換爲②(x+y,xy)(x + y, x - y),那麼①的曼哈頓距離等於②的切比雪夫距離。

切比雪夫距離dis=max(x2x1,y2y1)dis=max(|x_2-x_1|, |y_2-y_1|)

那麼對於點 ii 來說,不合法的點就變成了以 ii 點爲中心,邊長爲 2d\ 2d 的正方形內點的個數(不包括邊上的)
上述所說的所有的正方形當然會有重合的部分,所以我們可以選擇只統計每個正方形的左半邊。

我們用樹狀數組來維護某橫座標區間(xd,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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章