解題思路
統計切比雪夫距離不超過d的點對。
以邊長d的格桶將(x,y)分到(x//d,y//d)。若座標差皆≤d,桶索引每一軸之差必定≤1,只需搜尋九個相鄰桶。
新感測器與先前點比較,符合兩軸差距就增加答案,之後才放入自己的桶,因此每對僅計一次。
同桶任意兩點必互連;因每點鄰居少於10,桶中至多10點,九桶的候選量有常數界。未限定座標大小,使用任意精度整數。
Python期望 O(N)次雜湊操作,C++平衡樹 O(N log N)次比較,另乘整數位數成本;空間 O(N)個大整數。
Step-by-step animation
等邊格桶的鄰域搜尋逐步追蹤
步驟 1 / 3
步驟 1
d=3,前兩點(2,1)、(2,5)的y差4,不相連。
連結0
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
cpp_int ab(cpp_int x) {
return x < 0 ? -x : x;
}
int main() {
cpp_int d;
int n;
cin >> d >> n;
using P = pair<cpp_int, cpp_int>;
map<P, vector<P>> b;
ll ans = 0;
while (n--) {
cpp_int x, y;
cin >> x >> y;
cpp_int u = x / d, v = y / d;
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++) {
auto it = b.find({u + i, v + j});
if (it != b.end())
for (auto [a, c] : it->second)
if (ab(a - x) <= d && ab(c - y) <= d)
ans++;
}
b[{u, v}].push_back({x, y});
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。