best meeting point

There is an infinite integer grid at which N people have their houses on. They decide to unite at a common meeting place, which is someone's house. From any given cell, all 8 adjacent cells are reachable in 1 unit of time. eg: (x,y) can be reached from (x-1,y+1) in a single unit of time. Find a common meeting place which minimizes the sum of the travel times of all the persons.



这个题目可以参考之前做的加油站问题,只是一维简化版本

有n个加油站,选择中间的那个加油站,作为总加油站,其他加油站到它的距离最短


可以先把所有的点映射到x轴,找到一个点位于所有点的中位数位置

再把所有的点映射到Y轴,找到一个点位于所有点的中位数位置

这两条线的交点就是meeting place


struct POS 
{
        int x;
        int y;
};

bool CompX(POS a, POS b) { return a.x < b.x; }
bool CompY(POS a, POS b) { return a.y < b.y; }

POS FindMeetingPlace(POS a[], int n)
{
        assert(a && n>0);

        POS pos;
        sort(a, a+n, CompX);
        pos.x = a[n/2].x;

        sort(a, a+n, CompY);
        pos.y = a[n/2].y;

        return pos;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import randomimport multiprocessing# 定义目标函数,这里以一个简单的二维函数为例def target_func(x, y): return x ** 2 + y ** 2# 定义爬山算法,这里使用随机爬山算法def hill_climbing(start_point): current_point = start_point current_value = target_func(*current_point) while True: next_points = [(current_point[0] + random.uniform(-1, 1), current_point[1] + random.uniform(-1, 1)) for _ in range(10)] next_values = [target_func(*p) for p in next_points] next_point, next_value = min(zip(next_points, next_values), key=lambda x: x[1]) if next_value < current_value: current_point = next_point current_value = next_value else: break return current_point, current_value# 定义并行爬山函数def parallel_hill_climbing(num_workers, num_iterations, start_points): global_best_point, global_best_value = None, float('inf') pool = multiprocessing.Pool(num_workers) for i in range(num_iterations): results = pool.map(hill_climbing, start_points) best_point, best_value = min(results, key=lambda x: x[1]) if best_value < global_best_value: global_best_point, global_best_value = best_point, best_value start_points = [global_best_point] * len(start_points) return global_best_point, global_best_value# 测试代码if __name__ == '__main__': num_workers = 4 num_iterations = 10 start_points = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(num_workers)] best_point, best_value = parallel_hill_climbing(num_workers, num_iterations, start_points) print(f'Best point: {best_point}, best value: {best_value}')
最新发布
05-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值