|
| 1 | +import java.util.*; |
| 2 | +import java.io.*; |
| 3 | + |
| 4 | +public class JM_병원_거리_최소화하기 { |
| 5 | + static class Point { |
| 6 | + int y, x; |
| 7 | + public Point(int y, int x) { |
| 8 | + this.y = y; |
| 9 | + this.x = x; |
| 10 | + } |
| 11 | + } |
| 12 | + static int N; |
| 13 | + static int M; |
| 14 | + static List<Point> hospital; |
| 15 | + static List<Point> person; |
| 16 | + static int answer; |
| 17 | + static int[][] dist; |
| 18 | + |
| 19 | + private static int calc(int picked) { |
| 20 | + int sum = 0; |
| 21 | + for(int i = 0; i < person.size(); i++) { |
| 22 | + int pDist = Integer.MAX_VALUE; |
| 23 | + for(int j = 0; j < hospital.size(); j++) { |
| 24 | + if((picked & (1 << j)) == 0) continue; |
| 25 | + if(pDist > dist[i][j]) pDist = dist[i][j]; |
| 26 | + } |
| 27 | + sum += pDist; |
| 28 | + } |
| 29 | + return sum; |
| 30 | + } |
| 31 | + |
| 32 | + private static void pick(int next, int index, int picked) { |
| 33 | + if(index == M) { |
| 34 | + int currTotalSum = calc(picked); |
| 35 | + if(answer > currTotalSum) answer = currTotalSum; |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + for(int i = next; i < hospital.size(); i++) { |
| 40 | + pick(i + 1, index + 1, picked | (1 << i)); |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + private static void initDist() { |
| 46 | + for(int i = 0; i < person.size(); i++) { |
| 47 | + for(int j = 0; j < hospital.size(); j++) { |
| 48 | + dist[i][j] = Math.abs(person.get(i).y - hospital.get(j).y) + Math.abs(person.get(i).x - hospital.get(j).x); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public static void main(String[] args) throws IOException { |
| 54 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 55 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 56 | + N = Integer.parseInt(st.nextToken()); |
| 57 | + M = Integer.parseInt(st.nextToken()); |
| 58 | + |
| 59 | + hospital = new ArrayList<>(); |
| 60 | + person = new ArrayList<>(); |
| 61 | + |
| 62 | + for(int i = 0; i < N; i++) { |
| 63 | + st = new StringTokenizer(br.readLine()); |
| 64 | + for(int j = 0; j < N; j++) { |
| 65 | + int x = Integer.parseInt(st.nextToken()); |
| 66 | + if(x == 1) person.add(new Point(i, j)); |
| 67 | + else if(x == 2) hospital.add(new Point(i, j)); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + dist = new int[person.size()][hospital.size()]; |
| 72 | + initDist(); |
| 73 | + |
| 74 | + answer = Integer.MAX_VALUE; |
| 75 | + pick(0, 0, 0); |
| 76 | + System.out.println(answer); |
| 77 | + } |
| 78 | +} |
0 commit comments