aNotHeRNo0b
Senior Member
Java:
class Solution {
public static final int POSITION = 0;
public static final int LIMIT = 1;
public long minimumTotalDistance(List<Integer> robot, int[][] factory) {
Collections.sort(robot);
long[][][] memo = new long[robot.size()][factory.length][robot.size() + 1];
for (int i = 0; i < robot.size(); i++) {
for (int j = 0; j < factory.length; j++) {
Arrays.fill(memo[i][j], -1);
}
}
Arrays.sort(factory, (a, b) -> a[POSITION] - b[POSITION]);
return minimumMovement(0, 0, 1, robot, factory, memo);
}
public long minimumMovement(int curRobot, int curFactory, int curSlot, List<Integer> robotPositions, int[][] factory, long[][][] memo) {
if (curRobot == robotPositions.size() && curFactory == factory.length) {
return 0;
}
if (curFactory == factory.length) {
return 2L * 1_000_000_000 * 100 + 1;
}
if (curRobot == robotPositions.size()) {
return 0;
}
if (memo[curRobot][curFactory][curSlot] != -1) {
return memo[curRobot][curFactory][curSlot];
}
int nextFactory = curFactory, nextSlot = curSlot;
if (curSlot + 1 > factory[curFactory][LIMIT]) {
nextFactory = curFactory + 1;
nextSlot = 1;
} else {
nextSlot = curSlot + 1;
}
long minMove = minimumMovement(curRobot, nextFactory, nextSlot, robotPositions, factory, memo);
if (factory[curFactory][LIMIT] != 0) {
minMove = Math.min(
minMove,
minimumMovement(
curRobot + 1,
nextFactory,
nextSlot,
robotPositions,
factory,
memo
) + Math.abs(factory[curFactory][POSITION] - robotPositions.get(curRobot))
);
}
memo[curRobot][curFactory][curSlot] = minMove;
return minMove;
}
}

code cũ ảnh em up ở trên còn gì


