[파이썬]프로그래머스 2021 Dev Matching 다단계 칫솔 판매

Byeonghyeon Kim·2021년 5월 4일
0

알고리즘문제

목록 보기
73/93
post-thumbnail

링크

프로그래머스 2021 Dev Matching 다단계 칫솔 판매


트리를 딕셔너리를 이용해서 구현하고 탐색할 줄 알면 풀 수 있는 문제

딕셔너리를 활용해 트리를 구현하고 시작 노드에서 부모노드로 올라가면서 판매금액의 10%씩 부모노드의 돈으로 넘겨주면 된다.

트리와 돈 누적합을 구하는데 딕셔너리를 사용했다.


정답 코드

def solution(enroll, referral, seller, amount):
    
    tree = {'-' : 'root'}
    sell = {'-' : 0}
    for i in range(len(enroll)):
        child = enroll[i]
        parent = referral[i]
        sell[child] = 0
        tree[child] = parent

    for i in range(len(seller)):
        child = seller[i]
        parent = tree[child]
        money = amount[i] * 100
        sell[child] += money
        while True:
            commission = money // 10
            sell[child] -= commission
            sell[parent] += commission
            child = parent
            parent = tree[child]
            money = commission
            if parent == 'root':
                break
                
    ans = []
    for person in enroll:
        ans.append(sell[person])
    
    return ans

알게된 것👨‍💻

  • 딕셔너리를 잘 활용하면 문제가 쉬워진다.
profile
자기 주도 개발전 (개발, 발전)

0개의 댓글