Skip to content

Commit 62243d1

Browse files
authored
[20251003] PGM / Lv3 / 주사위 고르기 / 이강현
1 parent 1944839 commit 62243d1

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
```java
2+
import java.util.*;
3+
4+
class Solution {
5+
static int n;
6+
static int maxWin;
7+
static int[] answer;
8+
9+
public int[] solution(int[][] dice) {
10+
n = dice.length;
11+
maxWin = 0;
12+
13+
combination(new boolean[n], 0, 0, dice);
14+
15+
return answer;
16+
}
17+
18+
void combination(boolean[] selected, int idx, int count, int[][] dice) {
19+
if (count == n / 2) {
20+
int winCount = getWinCount(selected, dice);
21+
22+
if (winCount > maxWin) {
23+
maxWin = winCount;
24+
answer = getSelectedDice(selected);
25+
}
26+
return;
27+
}
28+
29+
if (idx == n) return;
30+
31+
selected[idx] = true;
32+
combination(selected, idx + 1, count + 1, dice);
33+
34+
selected[idx] = false;
35+
combination(selected, idx + 1, count, dice);
36+
}
37+
38+
int getWinCount(boolean[] selected, int[][] dice) {
39+
List<Integer> aList = new ArrayList<>();
40+
List<Integer> bList = new ArrayList<>();
41+
42+
makeSum(selected, dice, true, 0, 0, aList);
43+
makeSum(selected, dice, false, 0, 0, bList);
44+
45+
Collections.sort(bList);
46+
47+
int win = 0;
48+
for (int a : aList) {
49+
win += lowerBound(bList, a);
50+
}
51+
52+
return win;
53+
}
54+
55+
void makeSum(boolean[] selected, int[][] dice, boolean isA, int idx, int sum, List<Integer> list) {
56+
if (idx == n) {
57+
list.add(sum);
58+
return;
59+
}
60+
61+
if (selected[idx] == isA) {
62+
for (int num : dice[idx]) {
63+
makeSum(selected, dice, isA, idx + 1, sum + num, list);
64+
}
65+
} else {
66+
makeSum(selected, dice, isA, idx + 1, sum, list);
67+
}
68+
}
69+
70+
int lowerBound(List<Integer> list, int target) {
71+
int left = 0;
72+
int right = list.size();
73+
74+
while (left < right) {
75+
int mid = (left + right) / 2;
76+
if (list.get(mid) < target) {
77+
left = mid + 1;
78+
} else {
79+
right = mid;
80+
}
81+
}
82+
83+
return left;
84+
}
85+
86+
int[] getSelectedDice(boolean[] selected) {
87+
int[] result = new int[n / 2];
88+
int idx = 0;
89+
for (int i = 0; i < n; i++) {
90+
if (selected[i]) {
91+
result[idx++] = i + 1;
92+
}
93+
}
94+
return result;
95+
}
96+
}
97+
```

0 commit comments

Comments
 (0)