|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +/* |
| 5 | + * 병원 거리 최소화하기 |
| 6 | + */ |
| 7 | + |
| 8 | +public class DH_병원_거리_최소화하기 { |
| 9 | + static int N, M; |
| 10 | + static int[] dis; |
| 11 | + static int[] dr = {-1, 1, 0, 0}, dc = {0, 0, -1, 1}; |
| 12 | + static int[][] map; |
| 13 | + static ArrayList<Integer> people, hospitals; |
| 14 | + |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + initInput(); |
| 17 | + |
| 18 | + // hospitals.size() 개에서 m개의 병원 고르기 (조합) |
| 19 | + System.out.println(comb(0, 0, 0, hospitals.size())); |
| 20 | + } |
| 21 | + |
| 22 | + static int comb(int depth, int idx, int status, int size) { |
| 23 | + int result = Integer.MAX_VALUE; |
| 24 | + |
| 25 | + if(depth == M) { |
| 26 | + |
| 27 | + Arrays.fill(dis, Integer.MAX_VALUE); |
| 28 | + |
| 29 | + // 선택된 병원과 사람들 사이의 최소 거리 구하기 |
| 30 | + for(int i = 0; i < size; i++) { |
| 31 | + if((status & (1 << i)) == 0) continue; |
| 32 | + |
| 33 | + int pos = hospitals.get(i); |
| 34 | + int r = pos / N, c = pos % N; |
| 35 | + |
| 36 | + for(int k = 0; k < people.size(); k++) { |
| 37 | + int p = people.get(k); |
| 38 | + int pr = p / N, pc = p % N; |
| 39 | + |
| 40 | + int tmp = 0; |
| 41 | + tmp += Math.abs(pr - r) + Math.abs(pc - c); |
| 42 | + dis[k] = Math.min(dis[k], tmp); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + int minDis = 0; |
| 47 | + for(int d: dis) minDis += d; |
| 48 | + |
| 49 | + return minDis; |
| 50 | + } |
| 51 | + |
| 52 | + for(int i = idx; i < size; i++) { |
| 53 | + status |= (1 << i); |
| 54 | + result = Math.min(comb(depth + 1, i + 1, status, size), result); |
| 55 | + status ^= (1 << i); |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | + } |
| 60 | + |
| 61 | + static void initInput() throws Exception { |
| 62 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 63 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 64 | + |
| 65 | + N = Integer.parseInt(st.nextToken()); // map의 크기 |
| 66 | + M = Integer.parseInt(st.nextToken()); // M개의 병원 고르기 (조합) |
| 67 | + |
| 68 | + map = new int[N][N]; |
| 69 | + |
| 70 | + people = new ArrayList<Integer>(); |
| 71 | + hospitals = new ArrayList<Integer>(); // 병원들의 좌표 저장 |
| 72 | + |
| 73 | + for(int r = 0; r < N; r++) { |
| 74 | + st = new StringTokenizer(br.readLine()); |
| 75 | + |
| 76 | + for(int c = 0; c < N; c++) { |
| 77 | + map[r][c] = Integer.parseInt(st.nextToken()); |
| 78 | + if(map[r][c] == 0) continue; |
| 79 | + |
| 80 | + // 병원과 사람들의 좌표 저장 |
| 81 | + int pos = r * N + c; |
| 82 | + if(map[r][c] == 1) people.add(pos); |
| 83 | + if(map[r][c] == 2) hospitals.add(pos); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + dis = new int[people.size()]; |
| 88 | + } |
| 89 | +} |
0 commit comments