[백준] 1940번 : 주몽

Narcoker·2023년 6월 16일
0

코딩테스트

목록 보기
110/150

문제

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

풀이

Lower bound를 구해주는 bisect_left 라이브러리를 사용해서
갑옷을 만들어 낼 수 있는지 체크한다.

M 이 최대값인 10000000 이고 선택한 재료 1이 1이면 재료 2의 인덱스는
bisect_left([1,2,3,4], 9999999) 가 되는데 이 경우 반환값은 배열의 인덱스를 넘게된다.
따라서 반환값이 유효한 인덱스인지 체크해줘야 한다.

from bisect import bisect_left

N = int(input())
M = int(input())
mats = list(map(int, input().rstrip().split(" ")))


def solution(N, M, mats):
    answer = 0
    sorted_mats = sorted(mats)
    for i in range(N):
        target_index = bisect_left(sorted_mats, M - sorted_mats[i])
        if target_index < N and sorted_mats[i] + sorted_mats[target_index] == M:
            answer += 1
    print(answer // 2)


solution(N, M, mats)
profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글