|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class Permutation { |
| 4 | + private int n; |
| 5 | + private int r; |
| 6 | + private int[] now; // 현재 순열 |
| 7 | + private ArrayList<ArrayList<Integer>> result; // 모든 순열 |
| 8 | + |
| 9 | + public ArrayList<ArrayList<Integer>> getResult() { |
| 10 | + return result; |
| 11 | + } |
| 12 | + |
| 13 | + public Permutation(int n, int r) { |
| 14 | + this.n = n; |
| 15 | + this.r = r; |
| 16 | + this.now = new int[r]; |
| 17 | + this.result = new ArrayList<ArrayList<Integer>>(); |
| 18 | + } |
| 19 | + |
| 20 | + public void swap(int[] arr, int i, int j) { |
| 21 | + int temp = arr[i]; |
| 22 | + arr[i] = arr[j]; |
| 23 | + arr[j] = temp; |
| 24 | + } |
| 25 | + |
| 26 | + public void permutation(int[] arr, int depth) { |
| 27 | + // 현재 순열의 길이가 r일 때 결과 저장 |
| 28 | + if (depth == r) { |
| 29 | + ArrayList<Integer> temp = new ArrayList<>(); |
| 30 | + for (int i = 0; i < now.length; i++) { |
| 31 | + temp.add(now[i]); |
| 32 | + } |
| 33 | + result.add(temp); |
| 34 | + return; |
| 35 | + } |
| 36 | + for (int i = depth; i < n; i++) { |
| 37 | + swap(arr, i, depth); |
| 38 | + now[depth] = arr[depth]; |
| 39 | + permutation(arr, depth + 1); |
| 40 | + swap(arr, i, depth); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +class Solution { |
| 46 | + public int solution(int n, int[] weak, int[] dist) { |
| 47 | + // 길이를 2배로 늘려서 '원형'을 일자 형태로 변경 |
| 48 | + ArrayList<Integer> weakList = new ArrayList<Integer>(); |
| 49 | + for (int i = 0; i < weak.length; i++) { |
| 50 | + weakList.add(weak[i]); |
| 51 | + } |
| 52 | + for (int i = 0; i < weak.length; i++) { |
| 53 | + weakList.add(weak[i] + n); |
| 54 | + } |
| 55 | + // 투입할 친구 수의 최솟값을 찾아야 하므로 len(dist) + 1로 초기화 |
| 56 | + int answer = dist.length + 1; |
| 57 | + // 친구 정보를 이용해 모든 순열 계산 |
| 58 | + Permutation perm = new Permutation(dist.length, dist.length); |
| 59 | + perm.permutation(dist, 0); |
| 60 | + ArrayList<ArrayList<Integer>> distList = perm.getResult(); |
| 61 | + // 0부터 length - 1까지의 위치를 각각 시작점으로 설정 |
| 62 | + for (int start = 0; start < weak.length; start++) { |
| 63 | + // 친구를 나열하는 모든 경우 각각에 대하여 확인 |
| 64 | + for (int i = 0; i < distList.size(); i++) { |
| 65 | + int cnt = 1; // 투입할 친구의 수 |
| 66 | + // 해당 친구가 점검할 수 있는 마지막 위치 |
| 67 | + int position = weakList.get(start) + distList.get(i).get(cnt - 1); |
| 68 | + // 시작점부터 모든 취약한 지점을 확인 |
| 69 | + for (int index = start; index < start + weak.length; index++) { |
| 70 | + // 점검할 수 있는 위치를 벗어나는 경우 |
| 71 | + if (position < weakList.get(index)) { |
| 72 | + cnt += 1; // 새로운 친구를 투입 |
| 73 | + if (cnt > dist.length) { // 더 투입이 불가능하다면 종료 |
| 74 | + break; |
| 75 | + } |
| 76 | + position = weakList.get(index) + distList.get(i).get(cnt - 1); |
| 77 | + } |
| 78 | + } |
| 79 | + answer = Math.min(answer, cnt); // 최솟값 계산 |
| 80 | + } |
| 81 | + } |
| 82 | + if (answer > dist.length) { |
| 83 | + return -1; |
| 84 | + } |
| 85 | + return answer; |
| 86 | + } |
| 87 | +} |
0 commit comments