|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | +public class JY_병원_거리_최소화하기 { |
| 4 | + |
| 5 | + static int N, M; |
| 6 | + static int[][] g; |
| 7 | + static Map<Integer, Hospital> hMap; |
| 8 | + static List<Integer> tList; |
| 9 | + static int ans; |
| 10 | + static class Hospital { |
| 11 | + int num, x, y; |
| 12 | + |
| 13 | + public Hospital(int num, int x, int y) { |
| 14 | + super(); |
| 15 | + this.num = num; |
| 16 | + this.x = x; |
| 17 | + this.y = y; |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public String toString() { |
| 22 | + return "Hospital [num=" + num + ", x=" + x + ", y=" + y + "]"; |
| 23 | + } |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + public static void main(String[] args) throws IOException{ |
| 28 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 29 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 30 | + |
| 31 | + N = Integer.parseInt(st.nextToken()); |
| 32 | + M = Integer.parseInt(st.nextToken()); |
| 33 | + |
| 34 | + g = new int[N][N]; |
| 35 | + hMap = new HashMap<>(); |
| 36 | + int n = 0; |
| 37 | + for(int i=0; i<N; i++) { |
| 38 | + st = new StringTokenizer(br.readLine()); |
| 39 | + for(int j=0; j<N; j++) { |
| 40 | + g[i][j] = Integer.parseInt(st.nextToken()); |
| 41 | + if(g[i][j] == 2) { |
| 42 | + hMap.put(n, new Hospital(n, i, j)); |
| 43 | + n++; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + tList = new ArrayList<>(); |
| 49 | + ans = Integer.MAX_VALUE; |
| 50 | + // 최대 경우의 수 : 100(사람수) * 13C7 * 7 |
| 51 | + comb(0, 0); |
| 52 | + |
| 53 | + System.out.println(ans); |
| 54 | + } |
| 55 | + public static void comb(int depth, int start) { |
| 56 | + if(depth == M) { |
| 57 | + int score = find(tList); |
| 58 | + ans = Math.min(ans, score); |
| 59 | + return; |
| 60 | + } |
| 61 | + for(int i=start; i<hMap.size(); i++) { |
| 62 | + tList.add(i); |
| 63 | + comb(depth+1, i+1); |
| 64 | + tList.remove(tList.size()-1); |
| 65 | + } |
| 66 | + } |
| 67 | + public static int cal(int x1, int y1, int x2, int y2) { |
| 68 | + return Math.abs(x1-x2) + Math.abs(y1-y2); |
| 69 | + } |
| 70 | + public static int find(List<Integer> hList) { |
| 71 | + int total = 0; |
| 72 | + // 사람 반복 |
| 73 | + for(int i=0; i<N; i++) { |
| 74 | + for(int j=0; j<N; j++) { |
| 75 | + if(g[i][j] != 1) continue; |
| 76 | + int tmp = Integer.MAX_VALUE; |
| 77 | + // 병원 반복 |
| 78 | + for(int h : hList) { |
| 79 | + Hospital now = hMap.get(h); |
| 80 | + int dist = cal(i, j, now.x, now.y); |
| 81 | + tmp = Math.min(tmp, dist); |
| 82 | + } |
| 83 | + total += tmp; |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return total; |
| 88 | + } |
| 89 | + |
| 90 | +} |
0 commit comments