Skip to content

Commit 2255fe7

Browse files
committed
[BOJ] #18114. 블랙 프라이데이 / 골드5 / 투포인터 / 55분 / 실패
1 parent 13a75d3 commit 2255fe7

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import sys
2+
3+
input = sys.stdin.readline
4+
5+
# 입력
6+
N, C = map(int, input().split()) # N: 물건의 개수, C: 목표 무게
7+
items = list(map(int, input().split())) # 물건의 무게
8+
9+
items.sort() # 이분탐색을 위해 오름차순 정렬
10+
11+
12+
def binary_search(left, right, target):
13+
"""이분 탐색 함수: 배열에서 target이 존재하면 1, 없으면 0 반환"""
14+
while left <= right:
15+
mid = (left + right) // 2
16+
if items[mid] == target:
17+
return 1
18+
elif items[mid] > target:
19+
right = mid - 1
20+
else:
21+
left = mid + 1
22+
return 0
23+
24+
25+
def check(N, C):
26+
"""조건을 만족하는 조합이 있는지 확인"""
27+
28+
# 1개만 선택해도 되는 경우
29+
if C in items:
30+
return 1
31+
32+
# 2개 또는 3개 조합 확인
33+
start, end = 0, N - 1
34+
while start < end:
35+
total = items[start] + items[end]
36+
37+
# 2개로도 C를 만족하는 경우
38+
if total == C:
39+
return 1
40+
41+
# 2개의 물건 무게 합이 C보다 크다면 end를 왼쪽으로
42+
elif total > C:
43+
end -= 1
44+
# 2개의 물건 무게의 합이 C보다 작을 경우 = 3개를 확인해야 하는 경우
45+
else:
46+
diff = C - total # 부족한 무게 계산
47+
# 차이값이 start나 end에 위치한 값이 아니면서 동시에 부족한 무게를 이분탐색으로 찾는다.
48+
if items[start] != diff and items[end] != diff and binary_search(start, end, diff):
49+
return 1
50+
# 여기서 위의 조건이 성립되지 않는다면 start를 오른쪽으로 이동
51+
start += 1
52+
return 0
53+
54+
55+
# 정답 출력
56+
print(check(N, C))

0 commit comments

Comments
 (0)