본문 바로가기
Python/이분탐색

99클럽 코테 스터디 5일차 TIL + 백준 2470 두 용액 (파이썬)

by 유일리 2025. 1. 17.

※ 2470 두 용액

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

문제 해결 TIP

투 포인터 문제다! 이분 탐색에 꽂혀있는 나머지 mid를 어떻게 사용할까 고민했지만..결국 양쪽 끝값끼리 가운데로 가면서 더해주는 방식으로 풀었다.

1. 용액들을 먼저 정렬해준다.

2. start와 end 값은 0과 N - 1로 두고, 맨 처음 용액과 맨 끝 용액을 더한 절대값으로 answer 변수를 초기화해준다. point는 갱신될 두 용액의 값!

3. 두 포인터가 만나기 전까지 더해가며 값을 갱신해준다. 이때, 더한 두 용액의 값이 음수라면 start을 다음으로 큰 용액 값으로 변경해주고, 양수라면 end 포인트를 하나 왼쪽으로 이동시켜준다.

4. 두 용액의 합 중 절대값이 제일 작은 두 용액이 출력된다.

 

전체 코드

import sys

N = int(sys.stdin.readline())
solution = list(map(int,sys.stdin.readline().split()))
solution.sort()

start = 0
end = N - 1
answer = abs(solution[start]+solution[end])
point = [solution[start],solution[end]]

while start < end:
    solution_sum = solution[start]+solution[end]
    if answer > abs(solution_sum):
        answer = abs(solution_sum)
        point = [solution[start],solution[end]]
        if answer == 0:
            break
    if solution_sum < 0:
        start += 1
    else:
        end -= 1

print(point[0],point[1])

댓글