Greedy - 체육복

송다은·2024년 10월 15일
def solution(n, lost, reserve):
    answer = 0
    lend = [False] * len(reserve)
    lost_ = [False] * len(lost)
    for i in range(len(lost)): #0 1
        for j in range(len(reserve)):
            val = lost[i] - 1
            val2 = lost[i] + 1
            
            if val == reserve[j] and lend[j] == False: # -1이 reserve에 있고 빌리지 않은 옷이라면
                lost_[i] = True
                lend[j] = True
            elif val2 == reserve[j] or lend[j] == False: #+1이 reserve에 있고 빌리지 않은 옷이라면
                lost_[i] = True
                lend[j] = True
            else:
                continue
                
    #print(lost)        
    for i in lost_:
        if i == False :
            answer +=1 
    return n-answer

문제가 없어 보이는데 채점하면 자꾸 틀리는 예제가 있는 것이다....
알고보니 아래와 같은 예외사항도 생각해야 한다.

  • 옷을 잃어버렸으면서 여분옷을 가지고 있는 경우 (즉, lost아 reserve에 둘 다 해당되는 학생이 있는 경우)
  • 잃어버린 학생들의 배열이 "정렬"되어 있지 않은 경우

예제에 나와있지 않은 경우를 생각하는 것은 어려운 것 같다.

수정된 코드

def solution(n, lost, reserve):
    # 교집합(도난당한 학생이 여벌 체육복도 가지고 있는 경우) 처리
    lost_only = [l for l in lost if l not in reserve]
    reserve_only = [r for r in reserve if r not in lost]
    lost_only.sort()
    reserve_only.sort()
    # 체육복 빌려주기
    for r in reserve_only:
        if r - 1 in lost_only:  # 앞번호 학생이 도난당했으면
            lost_only.remove(r - 1)
        elif r + 1 in lost_only:  # 뒷번호 학생이 도난당했으면
            lost_only.remove(r + 1)
    
    # 체육복이 없는 학생 수를 전체 학생 수에서 뺀 값이 수업을 들을 수 있는 학생 수
    return n - len(lost_only)
profile
Anomaly Detection, AI Security, Multimodal

0개의 댓글