题解:AT_abc366_e [ABC366E] Manhattan Multifocal Ellipse

· · 题解

提供一个非常自然的思路。

题目中有 \displaystyle \sum_{i=1}^n (|x-x_i|+|y-y_i|) \leq D 这个限制,发现可以转化为 \displaystyle \sum_{i=1}^n |x-x_i|+\displaystyle \sum_{i=1}^n|y-y_i| \leq D,所以 x_i,y_i 是相互独立的,可以分别计算。

首先我们可以计算出 X_i 和 Y_i,其中 X_i 表示 \displaystyle \sum_{j=1}^n|i-x_j|,Y_i 是同理的。

考虑从 -2\times 10^6\sim 2\times 10^6 枚举 i,每个 X_i 可以在 \mathcal O(\log n) 的时间内求出。具体地,我们可以将 x 数组排序,预处理 x 数组的前缀和 fx 和后缀和 bx。对于枚举到的 i,lower_bound 查找在 x 数组中的位置,记为 l,则 X_i 为 i\times (l-1)-fx_{l-1}+bx_l-i\times(n-l+1)。其实就是计算数轴上各个点到 i 的距离之和。

对于计算 Y 数组是同理的。

记 cnt_i 为 \displaystyle \sum_{j=-2\times 10^6}^{2\times 10^6}[Y_j\le i],这个可以 \mathcal O(V) 求出。

枚举 i,对于 X_i\le d 的情况,计算 Y_i\le d-X_i 的数量,这个数量即为 cnt_{d-X_i}。

时间复杂度 \mathcal O(V\log n),其中 V 为 4\times 10^6。

unordered_map <int, int> X, Y;
const int Mi = -2e6, Ma = 2e6;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);

    cin >> n >> d;
    for (int i = 1; i <= n; i++) cin >> x[i] >> y[i];
    sort (x + 1, x + n + 1);
    for (int i = 1; i <= n; i++) fx[i] = fx[i - 1] + x[i];
    for (int i = n; i >= 1; i--) bx[i] = bx[i + 1] + x[i];
    for (int i = Mi; i <= Ma; i++) {
        if (i < x[1]) X[i] = fx[n] - i * n;
        else if (i > x[n]) X[i] = i * n - fx[n];
        else {
            int l = lower_bound (x + 1, x + n + 1, i) - x;
            X[i] = bx[l] - i * (n - l + 1) + i * (l - 1) - fx[l - 1];
        }
    }

    sort (y + 1, y + n + 1);
    for (int i = 1; i <= n; i++) fy[i] = fy[i - 1] + y[i];
    for (int i = n; i >= 1; i--) by[i] = by[i + 1] + y[i];
    for (int i = Mi; i <= Ma; i++) {
        if (i < y[1]) Y[i] = fy[n] - i * n;
        else if (i > y[n]) Y[i] = i * n - fy[n];
        else {
            int l = lower_bound (y + 1, y + n + 1, i) - y;
            Y[i] = by[l] - i * (n - l + 1) + i * (l - 1) - fy[l - 1];
        }
    }

    for (int i = Mi; i <= Ma; i++) {
        if (Y[i] > d) continue;
        cnt[Y[i]] ++;
    }
    for (int i = 1; i <= d; i++) cnt[i] += cnt[i - 1];

    for (int i = Mi; i <= Ma; i++) {
        if (X[i] > d) continue;
        int t = d - X[i];
        ans += cnt[t];
    }
    cout << ans << '\n';
    return 0;
}