map<pair<int,int>,int> mht_sum(const vector<Point>& pts, bool get_x) {
int n = (int)pts.size();
vector<int> left(n), right(n);
int sum = 0;
for(int i = 0; i < n; ++i) {
left[i] = sum;
sum += get_x ? pts[i].x : pts[i].y;
}
sum = 0;
for(int i = n - 1; i >= 0; --i) {
right[i] = sum;
sum += get_x ? pts[i].x : pts[i].y;
}
map<pair<int,int>,int> ret;
for(int i = 0; i < n; ++i) {
int p = get_x ? pts[i].x : pts[i].y;
ret[{pts[i].x,pts[i].y}] = p * i - left[i] + right[i] - (n-1-i) * p;
}
return ret;
}
int min_mht_dis(vector<Point> pts) {
sort(pts.begin(), pts.end(), [&](const Point& p0, const Point& p1){
return p0.x < p1.x;
});
auto x_sums = mht_sum(pts, true);
sort(pts.begin(), pts.end(), [&](const Point& p0, const Point& p1){
return p0.y < p1.y;
});
auto y_sums = mht_sum(pts, false);
int ret = INT_MAX;
for(int i = 0; i < pts.size(); ++i) {
ret = min(ret, x_sums[{pts[i].x,pts[i].y}] + y_sums[{pts[i].x,pts[i].y}]);
}
return ret;
}
No comments:
Post a Comment