[LeetCode] Best Position for a Service Centre

1515. Best Position for a Service Centre

A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.

Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.

In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:

Answers within 10-5 of the actual value will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#define db double
#define all(a) begin(a), end(a)
class Solution {
public:
double getMinDistSum(vector<vector<int>>& P) {
db t = 0, b = 100, l = 100, r = 0;
for(auto& p : P) {
t = max(t, (db) p[1]);
b = min(b, (db) p[1]);
l = min(l, (db) p[0]);
r = max(r, (db) p[0]);
}
db res = DBL_MAX, X = 0, Y = 0, gab = 10;
while(gab >= 1e-5) {
for(db x = l; x <= r; x += gab) {
for(db y = b; y <= t; y += gab) {
db distance = accumulate(all(P), 0.0, [&](db sum, vector<int>& p) {
return sum + sqrt((x-p[0])*(x-p[0]) + (y-p[1])*(y-p[1]));
});
if(res > distance) {
res = distance;
X = x;
Y = y;
}
}
}
l = X - gab;
r = X + 2*gab;
b = Y - gab;
t = Y + 2*gab;
gab /= 10;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/26/PS/LeetCode/best-position-for-a-service-centre/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.