# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1147947 | sossa_abel | Coin Collecting (JOI19_ho_t4) | Java | 0 ms | 0 KiB |
import java.io.*;
import java.util.*;
public class CoinCollecting {
static class State {
int x, y;
State(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof State)) return false;
State other = (State) obj;
return x == other.x && y == other.y;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Map<State, Integer> coinCount = new HashMap<>();
for (int i = 0; i < 2 * n; i++) {
String[] parts = br.readLine().split(" ");
int x = Integer.parseInt(parts[0]);
int y = Integer.parseInt(parts[1]);
State pos = new State(x, y);
coinCount.merge(pos, 1, Integer::sum);
}
long totalMoves = 0;
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= 2; y++) {
State target = new State(x, y);
int minDist = Integer.MAX_VALUE;
State closest = null;
for (Map.Entry<State, Integer> entry : coinCount.entrySet()) {
if (entry.getValue() > 0) {
State pos = entry.getKey();
int dist = Math.abs(pos.x - x) + Math.abs(pos.y - y);
if (dist < minDist) {
minDist = dist;
closest = pos;
}
}
}
if (closest != null) {
totalMoves += minDist;
coinCount.merge(closest, -1, Integer::sum);
}
}
}
System.out.println(totalMoves);
}
}