题解:AT_abc366_e [ABC366E] Manhattan Multifocal Ellipse
PineappleSummer · · 题解
提供一个非常自然的思路。
题目中有
首先我们可以计算出
考虑从 lower_bound 查找在
对于计算
记
枚举
时间复杂度
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;
}