Under construction

Still being built. Things may change

Do It Yourself?

Time limit10sMemory limit1024 MB

Summary
Each task can be done by its owner or any of the owner's bosses. Find the minimum sum of f_i times (tasks done by i) squared over all employees.
Level

Hard8 of 10

Topics
Tree, Dynamic programming
Solved
No attempts yet

Problem

You are the head of a group of nn employees in a company, including yourself. Each employee has an employee ID, an integer from 1 to nn, and your ID is 1. Employees are often called by their IDs for short: #11, #22, and so on. Every employee other than you has exactly one immediate boss, whose ID is smaller than theirs. A boss of an employee is defined recursively as follows.

  • If employee #ii is the immediate boss of employee #jj, then #ii is a boss of #jj.
  • If #ii is a boss of #jj and #jj is a boss of #kk, then #ii is a boss of #kk.

Every employee, including you, is initially assigned exactly one task. A task can be done by the employee who holds it or by any one of that employee's bosses. An employee can do any number of tasks, but doing many tasks is tiring. Employee #ii has a fatigability constant fif_i. If #ii does mm tasks in total, the fatigue level of #ii becomes fi×m2f_i \times m^2.

Minimize the sum of fatigue levels of all nn employees.

Input

The first line contains the number of employees nn (2≤n≤5×1052 \le n \le 5 \times 10^5).

The second line contains n−1n-1 integers b2,b3,…,bnb_2, b_3, \ldots, b_n, where bib_i is the immediate boss of employee #ii and 1≤bi<i1 \le b_i < i.

The third line contains nn integers f1,f2,…,fnf_1, f_2, \ldots, f_n, where fif_i is the fatigability constant of employee #ii and 1≤fi≤10121 \le f_i \le 10^{12}.

Output

Print the minimum possible sum of fatigue levels of all nn employees.

Hint

Figure J.1 shows the situations and solutions of the three samples.

In the first sample, the only optimal way is for every employee to do their own task. You should say 'Do it yourself!' to everyone.

In the second sample, the only optimal way is for employee #11 to do all the tasks. You should say 'Leave it to me!' to everyone.

In the third sample, one optimal way is as follows.

  • #11 does the tasks of #11 and #22. The fatigue level of #11 is 1×22=41 \times 2^2 = 4.
  • #22 does the task of #44. The fatigue level of #22 is 2×12=22 \times 1^2 = 2.
  • #33 does their own task. The fatigue level of #33 is 4×12=44 \times 1^2 = 4.
  • #44 does nothing. The fatigue level of #44 is 8×02=08 \times 0^2 = 0.

The sum of the fatigue levels is 4+2+4+0=104 + 2 + 4 + 0 = 10. Another optimal way is for #11, #22, and #33 to do their own tasks, and for #11 to also do the task of #44.

Examples3

  1. Example 1

    Input
    4
    1 1 2
    1 1 1 1
    
    Expected output
    4
    
  2. Example 2

    Input
    4
    1 1 2
    1 10 10 10
    
    Expected output
    16
    
  3. Example 3

    Input
    4
    1 1 2
    1 2 4 8
    
    Expected output
    10