|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int n, m, h, c; |
| 7 | + static List<int[]> houses = new ArrayList<>(); |
| 8 | + static List<int[]> chickens = new ArrayList<>(); |
| 9 | + static int[][] dist; |
| 10 | + static int[] pick; |
| 11 | + static int answer = Integer.MAX_VALUE; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 16 | + |
| 17 | + n = Integer.parseInt(st.nextToken()); |
| 18 | + m = Integer.parseInt(st.nextToken()); |
| 19 | + |
| 20 | + for (int i = 0; i < n; i++) { |
| 21 | + st = new StringTokenizer(br.readLine()); |
| 22 | + for (int j = 0; j < n; j++) { |
| 23 | + int v = Integer.parseInt(st.nextToken()); |
| 24 | + if (v == 1) houses.add(new int[]{i, j}); |
| 25 | + else if (v == 2) chickens.add(new int[]{i, j}); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + h = houses.size(); |
| 30 | + c = chickens.size(); |
| 31 | + |
| 32 | + dist = new int[h][c]; |
| 33 | + for (int h = 0; h < Main.h; h++) { |
| 34 | + int hx = houses.get(h)[0], hy = houses.get(h)[1]; |
| 35 | + for (int k = 0; k < Main.c; k++) { |
| 36 | + int cx = chickens.get(k)[0], cy = chickens.get(k)[1]; |
| 37 | + dist[h][k] = Math.abs(hx - cx) + Math.abs(hy - cy); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + pick = new int[m]; |
| 42 | + dfs(0, 0); |
| 43 | + |
| 44 | + System.out.println(answer); |
| 45 | + } |
| 46 | + |
| 47 | + static void dfs(int start, int depth) { |
| 48 | + if (depth == m) { |
| 49 | + int sum = 0; |
| 50 | + for (int h = 0; h < Main.h; h++) { |
| 51 | + int best = Integer.MAX_VALUE; |
| 52 | + for (int p = 0; p < m; p++) { |
| 53 | + best = Math.min(best, dist[h][pick[p]]); |
| 54 | + } |
| 55 | + sum += best; |
| 56 | + if (sum >= answer) return; |
| 57 | + } |
| 58 | + answer = Math.min(answer, sum); |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + for (int i = start; i < c; i++) { |
| 63 | + pick[depth] = i; |
| 64 | + dfs(i + 1, depth + 1); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +``` |
0 commit comments