하루일문
[백준] 13777번 Hunt The Rabbit(파이썬) 본문
문제
13777번: Hunt The Rabbit
For each line of input, output the numbers of all envelopes opened, in the order they were opened, until the rabbit is found. Each number must be on the same line separated by a space from the previous number.
www.acmicpc.net
코드
while True:
start, end = 1, 50
N = int(input())
# N이 0이면 반복을 끝낸다
if N == 0:
break
while True:
# start와 end의 중간을 구한다
n = (start + end) // 2
# 중간을 프린트
print(n, end=' ')
# n과 N이 동일하지면 반복 끝낸다
if n == N:
break
# 중간 수보다 작다면 end를 줄인다
elif n > N:
end = n - 1
# 중간수 보다 크다면 start를 늘린다
else:
start = n + 1
# 반복이 끝나면 출력 줄을 바꾼다.
print(sep = '\n')
해설
이진탐색의 기본 문제이다. 중간 부분을 구하면서 계속하여 범위를 줄어나가는 식으로 풀이하였다.
'algorithm > baekjoon' 카테고리의 다른 글
[백준] 1654번 랜선 자르기(파이썬)) (0) | 2023.04.13 |
---|---|
[백준] 별찍기 -3(파이썬) (1) | 2023.04.10 |
[백준] 1535번 안녕(파이썬) (0) | 2023.04.08 |
[백준] 2579번 계단 오르기(파이썬) (0) | 2023.04.07 |
[백준] 14501번 퇴사(파이썬) (0) | 2023.04.06 |