写一个leetcode第1515题题解
时间: 2023-03-25 20:03:16 浏览: 302
好的,我可以回答这个问题。LeetCode 第 1515 题是 "Best Position for a Service Centre",即寻找服务中心的最佳位置。这道题可以使用梯度下降算法来解决,具体实现可以参考以下代码:
```c
double getDistance(double x1, double y1, double x2, double y2) {
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
double getCost(vector<vector<int>>& positions, double x, double y) {
double cost = ;
for (auto& pos : positions) {
cost += getDistance(pos[], pos[1], x, y);
}
return cost;
}
double getMinCost(vector<vector<int>>& positions, double x, double y, double delta) {
double cost = getCost(positions, x, y);
while (delta > 1e-7) {
bool found = false;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
double nx = x + delta * i;
double ny = y + delta * j;
double ncost = getCost(positions, nx, ny);
if (ncost < cost) {
cost = ncost;
x = nx;
y = ny;
found = true;
}
}
}
if (!found) {
delta /= 2;
}
}
return cost;
}
double getMinDistSum(vector<vector<int>>& positions) {
double x = , y = , delta = 100;
for (auto& pos : positions) {
x += pos[];
y += pos[1];
}
x /= positions.size();
y /= positions.size();
return getMinCost(positions, x, y, delta);
}
```
这段代码实现了一个函数 `getMinDistSum`,它接受一个二维向量 `positions`,表示所有服务中心的位置,返回一个浮点数,表示所有客户到最佳服务中心的距离和的最小值。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)