Appeal to the Audience

Time limit1sMemory limit512 MB

Summary
Assign k given skill values to the k leaves of a rooted tree to maximize the sum over all internal nodes of the skill values in that node's subtree's leaves.
Level

Medium7 of 10

Topics
Tree, Greedy, Sorting, DFS
Solved
No attempts yet

Problem

You are the director of the upcoming Bordfite Arena Progaming Competition. You have invited a bunch of players and are now setting up the matches for the knockout tournament that will determine the winner. As you may know, Bordfite Arena is a game that heavily rewards skill and very little luck is involved. This implies that whenever any number of players play a game of Bordfite Arena, the most skilled player will always win! Hence the winner of the tournament is already known, and you are a bit worried about this. How will you appease the audience?

You embark on a short quest to find out what the audience finds interesting. No surprises there: people find it most interesting when they see skillful players compete. Whenever a match is played, the happiness the audience gets from a match is the sum of the skill levels of the players. The total happiness the audience gets from the tournament is the sum of the happiness obtained during all matches. This is very useful information, because of course you want the audience to be as happy as possible at the end of the tournament.

Moreover, you invested some time to ask people what kind of knockout format they like. It turns out that instead of the plain old binary tree for the knockout schedule, they prefer a specific weird-looking rooted tree, and so you decide to use that. This means the final step for you to complete is to divide the players over the leaves of the given tree so that over the entire tournament, the happiness of the audience is maximized.

Input

  • The first line contains integers 3≤n≤1053 \le n \le 10^5 and 1≤k≤n−11 \le k \le n - 1, the number of nodes of the tree and the number of players. The nodes are labelled 00 through n−1n - 1, and 00 is the root of the tree.
  • The second line contains kk integers 0≤a1,…,ak≤1090 \le a_1, \ldots, a_k \le 10^9, denoting the skill values of the players.
  • Then follow n−1n - 1 lines, the iith of which (1≤i≤n−11 \le i \le n - 1) contains the parent 0≤pi<i0 \le p_i < i of node ii.

It is guaranteed that the tree has exactly kk leaves and that there are no nodes with exactly one child.

Output

  • Output the maximal possible happiness the audience can obtain from this tournament.

Examples2

  1. Example 1

    Input
    5 3
    5 4 3
    0
    0
    1
    1
    
    Expected output
    17
    
  2. Example 2

    Input
    11 7
    30 5 15 1 3 100 50
    0
    0
    1
    0
    2
    5
    2
    5
    5
    1
    
    Expected output
    454