Processing math: 100%

목차

대기업 승범이네

ps
링크acmicpc.net/…
출처BOJ
문제 번호17831
문제명대기업 승범이네
레벨플래티넘 5
분류

트리 DP

시간복잡도O(n)
인풋사이즈n<=200,000
사용한 언어Python
제출기록96920KB / 936ms
최고기록936ms
해결날짜2021/11/05

풀이

코드

"""Solution code for "BOJ 17831. 대기업 승범이네".

- Problem link: https://www.acmicpc.net/problem/17831
- Solution link: http://www.teferi.net/ps/problems/boj/17831

Tags: [DP] [DP on Tree]
"""

from teflib import ttree


def main():

    def calc_dp(subtree_vals, root):
        val_without_root = max_inc_with_root = 0
        for child, sub_val, sub_val_without_root in subtree_vals:
            val_without_root += sub_val
            inc = A[root] * A[child] - sub_val + sub_val_without_root
            max_inc_with_root = max(max_inc_with_root, inc)
        return (root, val_without_root + max_inc_with_root, val_without_root)

    N = int(input())
    bosses = [int(x) for x in input().split()]
    A = [int(x) for x in input().split()]

    tree = [[] for _ in range(N)]
    for i, boss in enumerate(bosses, 1):
        tree[i].append(boss - 1)
        tree[boss - 1].append(i)

    print(ttree.dp_on_tree(tree, calc_dp, 0)[1])


if __name__ == '__main__':
    main()