Skip to content

Commit 9964fc4

Browse files
authored
[20260131] BOJ / G1 / 부분수열의 합 2 / 한종욱
1 parent 81e077e commit 9964fc4

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static int[] arr;
9+
private static List<Integer> left, right;
10+
private static int N, S;
11+
12+
public static void main(String[] args) throws IOException {
13+
init();
14+
15+
long answer = 0;
16+
17+
for (int l : left) {
18+
answer += upperBound(l) - lowerBound(l);
19+
}
20+
21+
if (S == 0) answer--;
22+
23+
bw.write(answer + "");
24+
bw.flush();
25+
bw.close();
26+
br.close();
27+
}
28+
29+
private static void init() throws IOException {
30+
StringTokenizer st = new StringTokenizer(br.readLine());
31+
N = Integer.parseInt(st.nextToken());
32+
S = Integer.parseInt(st.nextToken());
33+
34+
arr = new int[N];
35+
left = new ArrayList<>();
36+
right = new ArrayList<>();
37+
38+
st = new StringTokenizer(br.readLine());
39+
for (int i = 0; i < N; i++) {
40+
arr[i] = Integer.parseInt(st.nextToken());
41+
}
42+
43+
subSum(0, N/2, 0, left);
44+
subSum(N/2, N, 0, right);
45+
46+
Collections.sort(left);
47+
Collections.sort(right);
48+
}
49+
50+
private static void subSum(int index, int end, int sum, List<Integer> list) {
51+
if (index == end) {
52+
list.add(sum);
53+
return;
54+
}
55+
56+
subSum(index+1, end, sum, list);
57+
subSum(index+1, end, sum+arr[index], list);
58+
}
59+
60+
private static int upperBound(int target) {
61+
int start = 0;
62+
int end = right.size()-1;
63+
64+
while (start <= end) {
65+
int mid = start + (end - start) / 2;
66+
67+
if (target + right.get(mid) > S) {
68+
end = mid-1;
69+
} else {
70+
start = mid+1;
71+
}
72+
}
73+
74+
return start;
75+
}
76+
77+
private static int lowerBound(int target) {
78+
int start = 0;
79+
int end = right.size()-1;
80+
81+
while (start <= end) {
82+
int mid = start + (end - start) / 2;
83+
84+
if (target + right.get(mid) >= S) {
85+
end = mid-1;
86+
} else {
87+
start = mid+1;
88+
}
89+
}
90+
91+
return start;
92+
}
93+
}
94+
```

0 commit comments

Comments
 (0)