Skip to content
Rain Hu's Workspace
Go back

2463

Rain Hu

2463. Minimum Total Distance Traveled


一、題目

There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.

The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.

All the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.

At any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.
Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.

Note that

ex1 Example 1:

ex2 Example 2:

Constraints:


二、分析

long long minimumTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
    map<int,int> mp;
    long long res = 0;
    for (auto f : factory) {
        if (f[1] == 0) continue;
        mp[f[0]] = f[1];
    }
    for (auto r : robot) {
        auto it = mp.lower_bound(r);
        if (it == mp.end()) {
            it--;
        } else if (it != mp.begin()){
            auto right = it--;
            if (r - it->first > right->first - r) {
                it = right;
            }
        }

        res += abs(it->first - r);
        if (it->second == 1) {
            mp.erase(it);
        } else {
            it->second--;
        }
    }

三、解題

1. DP

vector<vector<long long>> dp;
long long minimumTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
    long long res = 0;
    vector<int> fac;
    for (auto f : factory) {        // 將 factory 扁平化成 1d array
        int times = f[1];
        while (times--) {
            fac.push_back(f[0]);
        }
    }
    dp = vector<vector<long long>>(robot.size()+1, vector<long long>(fac.size()+1, -1));
    sort(robot.begin(), robot.end());
    sort(fac.begin(), fac.end());
    return dfs(robot, fac, 0, 0);
}
long long dfs(vector<int>& robot, vector<int>& fac, int i, int j) {
    if (i == robot.size()) return 0;    // 當機器人都排列完畢,為終止條件
    if (j == fac.size()) return (long long) (LONG_MAX/2);  // 工廠空缺空用了,傳回一個有效的大數,使之不會是答案
    if (dp[i][j] != -1) return dp[i][j];
    dp[i][j] = min(
        dfs(robot, fac, i+1, j+1) + (long long)abs(robot[i]-fac[j]),    // ith 機器人選擇 jth 工廠空位
        dfs(robot, fac, i, j+1)                                         // ith 機器人不選擇 jth 工廠空位
    );
    return dp[i][j];
}

回目錄 Catalog


Share this post on:

Previous
1834
Next
[Statistics] a群體與b群體各別標準差求整體標準差