leetcode1515_GeometricMedian

//欧式距离的和
template<typename t1, typename t2>
double distsum(vector<t1> &currp, vector<vector<t2>>& positions)
{
	double sum = 0.000000000;
	for (const auto &p : positions) {
		double distx = (double)abs(p[0] - currp[0]);
		double disty = (double)abs(p[1] - currp[1]);
		sum += sqrt((distx * distx) + (disty * disty));
	}
	return sum;
}

class Solution {
public:
    double getMinDistSum(vector<vector<int>>& positions) {
    double lower_limit = 1e-8;//这里和精度息息相关,非常重要
	vector<double> currp(2);
	for (const auto &p : positions) {
		currp[0] += (double)p[0];
		currp[1] += (double)p[1];
	}
	currp[0] /= double(positions.size());
	currp[1] /= double(positions.size());

	double minimum_distance = distsum(currp, positions);
	double test_distance = 5.000000000;//
	int flag = 0;
	//四方向的方向向量
	vector<vector<double>> test_point{ { -1.00000000, 0.00000000 },{ 0.00000000, 1.00000000 },{ 1.00000000, 0.00000000 },{ 0.00000000, -1.00000000 } };
	//到指定精度才能退出
	while (test_distance > lower_limit) {
		flag = 0;
		for (const auto &p : test_point) {
			vector<double> newpoint(2);
			newpoint[0] = currp[0] + (double)test_distance*p[0];
			newpoint[1] = currp[1] + (double)test_distance*p[1];

			double newd = distsum(newpoint, positions);

			if (newd < minimum_distance) {
				minimum_distance = newd;
				currp[0] = newpoint[0];
				currp[1] = newpoint[1];
				flag = 1;
				break;
			}
		}
		if (flag == 0)
			test_distance /= 2.0000000;
	}
	return minimum_distance;
    }
};

这道题最大的问题就是精度,需要注意数值的转换,以及阈值的设置。

大概思路:

  1. 求几何平均中心,值得注意的是这道题求的“中心”并不等于几何中心。[4]
  2. 四方向迫近,每次移动后步长折半,这里有点“退火”算法/梯度下降的意思。

我看这道题也有大佬使用weiszfeld’s求解,也很不错。
顺便附上一篇论文,讲了很多可用于求解的算法,大佬可以尝试复现哈[5]


Reference:
[1] https://www.geeksforgeeks.org/geometric-median/
[2] https://zxi.mytechroad.com/blog/geometry/leetcode-1515-best-position-for-a-service-centre/
[3] https://hankin2015.github.io/2018/09/22/20180922Weiszfeld/
[4] 维基百科的解释
[5] 论文
[6] https://stackoverflow.com/questions/12934213/how-to-find-out-geometric-median

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值