코딩 테스트/프로그래머스
다단계 칫솔 판매
땅어
2021. 7. 5. 11:47
728x90
300x250
문제
https://programmers.co.kr/learn/courses/30/lessons/77486
코딩테스트 연습 - 다단계 칫솔 판매
민호는 다단계 조직을 이용하여 칫솔을 판매하고 있습니다. 판매원이 칫솔을 판매하면 그 이익이 피라미드 조직을 타고 조금씩 분배되는 형태의 판매망입니다. 어느정도 판매가 이루어진 후,
programmers.co.kr
나의 풀이
뭔가 그래프 문제라서 복잡한 알고리즘을 써야할 줄 알았는데 생각보다 간단하게 해결했다.
자식-부모의 pair로 이루어진 dictionary를 활용해 반복적으로 돈을 분배하면 된다. 이 때 반복문의 종료 조건은 center까지 도달해 분배가 끝나거나 혹은 나눌 돈의 10%가 1원 미만(문제에서 주어진 종료조건)이다. 문제의 조건에서 10%를 계산할 땐 원 단위까지만 취급한다고 했기 때문에 int() 형변환을 사용해준다.
코드
def solution(enroll, referral, seller, amount):
child_parent = {}
for c,p in zip(enroll,referral):
child_parent[c] = "center" if p=='-' else p
person_money = {"center":0} # 각 사람마다 얼마를 버는지 저장
for p in enroll:
person_money[p] = 0
for s,m in zip(seller,amount):
money = m*100
p = child_parent[s]
person_money[s] += money
while True:
# 종료조건
if money*0.1<1:
break
else:
person_money[s] -= int(money*0.1)
person_money[p] += int(money*0.1)
money = money*0.1
s = p
if s=='center':
break
p = child_parent[s]
ans = []
for p in enroll:
ans.append(person_money[p])
return ans
728x90
300x250