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()