# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1148096 | pereira_oliver | Coin Collecting (JOI19_ho_t4) | Java | 0 ms | 0 KiB |
import java.util.*;
public class Main {
static class Coin {
long x, y;
Coin(long x, long y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
List<Coin> coins = new ArrayList<>();
for (int i = 0; i < 2 * N; i++) {
long x = sc.nextLong();
long y = sc.nextLong();
coins.add(new Coin(x, y));
}
long result = calculateMinMoves(N, coins);
System.out.println(result);
}
static long calculateMinMoves(int N, List<Coin> coins) {
long totalMoves = 0;
List<Coin> targets = new ArrayList<>();
for (int x = 1; x <= N; x++) {
targets.add(new Coin(x, 1));
targets.add(new Coin(x, 2));
}
boolean[] usedCoins = new boolean[2 * N];
boolean[] usedTargets = new boolean[2 * N];
for (int t = 0; t < 2 * N; t++) {
long minDist = Long.MAX_VALUE;
int bestCoin = -1;
for (int c = 0; c < 2 * N; c++) {
if (!usedCoins[c]) {
long dist = manhattanDistance(coins.get(c), targets.get(t));
if (dist < minDist) {
minDist = dist;
bestCoin = c;
}
}
}
usedCoins[bestCoin] = true;
totalMoves += minDist;
}
return totalMoves;
}
static long manhattanDistance(Coin from, Coin to) {
return Math.abs(from.x - to.x) + Math.abs(from.y - to.y);
}
}