LeetCode #1066. Campus Bikes II

题目描述:

On a campus represented as a 2D grid, there are N workers and M bikes, with N <= M. Each worker and bike is a 2D coordinate on this grid.

We assign one unique bike to each worker so that the sum of the Manhattan distances between each worker and their assigned bike is minimized.

The Manhattan distance between two points p1 and p2 is Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|.

Return the minimum possible sum of Manhattan distances between each worker and their assigned bike.

Example 1:

 

Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: 6
Explanation: 
We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6.

Example 2:

 

Input: workers = [[0,0],[1,1],[2,0]], bikes = [[1,0],[2,2],[2,1]]
Output: 4
Explanation: 
We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4.

Note:

  1. 0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000
  2. All worker and bike locations are distinct.
  3. 1 <= workers.length <= bikes.length <= 10
class Solution {
public:
    int assignBikes(vector<vector<int>>& workers, vector<vector<int>>& bikes) {
        dist=INT_MAX;
        int cur=0;
        DFS(workers,bikes,0,cur,0);
        return dist;
    }
    
    void DFS(vector<vector<int>>& workers, vector<vector<int>>& bikes, int mask, int cur, int i)
    {
        if(cur>=dist) return;
        if(i==workers.size())
        {
            dist=min(dist,cur);
            return;
        }

        for(int j=0;j<bikes.size();j++)
        {
            if(((1<<j)&mask)>0) continue;
            mask+=(1<<j);
            DFS(workers,bikes,mask,cur+manhattan_dist(workers[i],bikes[j]),i+1);
            mask-=(1<<j);
        }
    }
    
    int manhattan_dist(const vector<int>& a, const vector<int>& b)
    {
        return abs(a[0]-b[0])+abs(a[1]-b[1]);
    }
    
private:
    int dist;
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值