# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1147335 | aldo2902 | Coin Collecting (JOI19_ho_t4) | Pypy 3 | 0 ms | 0 KiB |
import java.util.*;
public class CoinCollecting {
private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public static int bfs(int[] start, int[] target) {
Queue<int[]> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
queue.add(new int[]{start[0], start[1], 0}); // {x, y, distancia}
visited.add(start[0] + "," + start[1]);
while (!queue.isEmpty()) {
int[] current = queue.poll();
int x = current[0], y = current[1], dist = current[2];
if (x == target[0] && y == target[1]) {
return dist;
}
for (int[] dir : DIRECTIONS) {
int nx = x + dir[0];
int ny = y + dir[1];
String key = nx + "," + ny;
if (!visited.contains(key)) {
visited.add(key);
queue.add(new int[]{nx, ny, dist + 1});
}
}
}
return Integer.MAX_VALUE;
}
public static int solveCoinCollecting(int N, List<int[]> coinPositions) {
List<int[]> targets = new ArrayList<>();
for (int x = 1; x <= N; x++) {
for (int y = 1; y <= 2; y++) {
targets.add(new int[]{x, y});
}
}
int totalMoves = 0;
Set<String> usedTargets = new HashSet<>();
for (int[] coin : coinPositions) {
int minMoves = Integer.MAX_VALUE;
int[] bestTarget = null;
for (int[] target : targets) {
String targetKey = target[0] + "," + target[1];
if (!usedTargets.contains(targetKey)) {
int moves = bfs(coin, target);
if (moves < minMoves) {
minMoves = moves;
bestTarget = target;
}
}
}
totalMoves += minMoves;
if (bestTarget != null) {
usedTargets.add(bestTarget[0] + "," + bestTarget[1]);
}
}
return totalMoves;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
List<int[]> coinPositions = new ArrayList<>();
for (int i = 0; i < 2 * N; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
coinPositions.add(new int[]{x, y});
}
int result = solveCoinCollecting(N, coinPositions);
System.out.println(result);
scanner.close();
}
}