[python] 백준 2467번 용액

Youngseo Lee·2024년 8월 11일

이진탐색

목록 보기
4/5

백준 2467번 용액

https://www.acmicpc.net/problem/2467

문제

풀이

어쨌거나 두 수의 합을 구하는 문제. 더했을 때 0이랑 제일 근접한 두 수 출력.
쉽게 하는 방법: 0 일 때 exit() 해서 코드 종료 시키기

n = int(input())
mlist = list(map(int, input().split()))

start = 0
end = n-1
left = 0
right = n-1

closetozero = float('inf')


while start < end:
    temp = mlist[start] + mlist[end]

    if abs(temp) < abs(closetozero):
        closetozero = temp
        left = start 
        right = end 

    if temp == 0:
        print(mlist[start], mlist[end])
        exit()
    
    elif temp > 0:
        end = end - 1
    
    else:
        start = start + 1

print(mlist[left], mlist[right])

만약 abs(temp) 보다 abs(closetozero)가 크면, closetozero를 temp로 바꿔주고, left와 right 도 start 와 끝으로 업데이트 해준다.

📌 주의

  • start 와 end 말고도 나중에 정답을 출력할 때 필요한 left 와 right 도 필요하다.
  • while start < end: 이 한 줄만 먼저 적고 시작하면 도움이 될 듯.
  • exit() 과 float('inf')는 외워두기.
profile
leenthepotato

0개의 댓글