import java.util.*;
public class joi2019_ho_t4 {
public static long minOperations(int N, int[][] coins) {
List<int[]> targetPositions = new ArrayList<>();
for (int x = 1; x <= N; x++) {
targetPositions.add(new int[]{x, 1}); // Primera fila para cada x
targetPositions.add(new int[]{x, 2}); // Segunda fila para cada x
}
Arrays.sort(coins, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
targetPositions.sort((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// Variable para acumular el número total de operaciones
long totalOperations = 0;
// Calculamos la suma de las distancias Manhattan entre cada moneda y su posición objetivo
for (int i = 0; i < 2 * N; i++) {
int[] coin = coins[i];
int[] target = targetPositions.get(i);
totalOperations += Math.abs(coin[0] - target[0]) + Math.abs(coin[1] - target[1]);
}
return totalOperations;
}
public static void main(String[] args) {
// Leer la entrada
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); // Número de monedas, y el ancho de la cuadrícula
int[][] coins = new int[2 * N][2];
// Leer las posiciones de las monedas
for (int i = 0; i < 2 * N; i++) {
coins[i][0] = sc.nextInt();
coins[i][1] = sc.nextInt();
}
// Llamar al método para obtener el número mínimo de operaciones
long result = minOperations(N, coins);
// Imprimir el resultado
System.out.println(result);
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |