목차

매출 하락 최소화

ps
링크programmers.co.kr/…
출처프로그래머스
문제 번호72416
문제명매출 하락 최소화
레벨Level 4
분류

DP

시간복잡도O(n)
인풋사이즈n<=300,000
사용한 언어Python
해결날짜2021/01/29
출처

ps:problems:programmers:2021_kakao_blind_recruitment

풀이

코드

"""Solution code for "Programmers 72416. 매출 하락 최소화".

- Problem link: https://programmers.co.kr/learn/courses/30/lessons/72416
- Solution link: http://www.teferi.net/ps/problems/programmers/72416
"""

import functools


def solution(sales, links):

    @functools.lru_cache(maxsize=None)
    def min_sales(node, should_include_root):
        children_sum = sum(min_sales(c, False) for c in children[node])
        sales_including_root = sales[node] + children_sum
        if should_include_root:
            return sales_including_root
        sales_without_root = children_sum + min(
            (min_sales(c, True) - min_sales(c, False) for c in children[node]),
            default=0)
        return min(sales_including_root, sales_without_root)

    children = [[] for _ in sales]
    for a, b in links:
        children[a - 1].append(b - 1)
    return min_sales(0, False)