Approach
Sorting and greedy selection
For Minimum Total Distance Traveled, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 36 lines of C++ from the credited upstream file 2463.cpp.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long minimumTotalDistance(vector<int>& robot,4 vector<vector<int>>& factory) {5 ranges::sort(robot);6 ranges::sort(factory);7 vector<vector<vector<long>>> mem(8 robot.size(),9 vector<vector<long>>(factory.size(), vector<long>(robot.size())));10 return minimumTotalDistance(robot, factory, 0, 0, 0, mem);11 }12 13 private:14 15 16 long minimumTotalDistance(const vector<int>& robot,17 const vector<vector<int>>& factory, int i, int j,18 int k, vector<vector<vector<long>>>& mem) {19 if (i == robot.size())20 return 0;21 if (j == factory.size())22 return LONG_MAX;23 if (mem[i][j][k] > 0)24 return mem[i][j][k];25 const long skipFactory =26 minimumTotalDistance(robot, factory, i, j + 1, 0, mem);27 const int position = factory[j][0];28 const int limit = factory[j][1];29 const long useFactory =30 limit > k ? minimumTotalDistance(robot, factory, i + 1, j, k + 1, mem) +31 abs(robot[i] - position)32 : LONG_MAX / 2;33 return mem[i][j][k] = min(skipFactory, useFactory);34 }35};36