#P5533. [CCO 2019] Winter Driving

[CCO 2019] Winter Driving

Description

There are NN cities in the Northern White Empire, numbered from 11 to NN. In city ii, there are AiA_i residents.

There are N1N - 1 roads, numbered from 22 to NN. Road jj connects city jj and city PjP_j, where Pj<jP_j \lt j. Each city is connected to at most 36 roads.

In winter, dangerous driving conditions cause the government to enforce traffic control, and all roads become one-way highways. That is, for each road jj, it becomes either a one-way highway from city jj to city PjP_j, or a one-way highway from city PjP_j to city jj.

Now, every resident wants to send holiday cards to all other citizens. However, to send a holiday card from city XX to city YY, it must be possible to travel from XX to YY using the highways, or X=YX = Y.

Find the maximum total number of cards that can be delivered after all roads are converted into one-way highways.

Input Format

The first line contains a positive integer NN.

The second line contains NN positive integers A1A_1 to ANA_N.

The third line contains N1N - 1 positive integers P2P_2 to PNP_N.

Output Format

One line containing a positive integer, the maximum total number of holiday cards that can be delivered.

4
3 3 4 1
1 2 1
67

Hint

Sample Explanation

One possible way is to convert:

avatar

into:

avatar

Then, each resident in city 3 can send 3 cards to city 3, 3 cards to city 2, 3 cards to city 1, and 1 card to city 4. So city 3 can send a total of 40 cards.

Similarly, city 2 can send 18 cards in total, city 1 can send 9 cards in total, and city 4 cannot send any cards.

So the answer is 40+18+9+0=6740 + 18 + 9 + 0 = 67.

Constraints

2N2000002 \le N \le 200\,000

For any valid ii, 1Ai100001 \le A_i \le 10\,000

For any valid jj, 1Pjj1 \le P_j \le j

Let DD be the number of roads connected to any city. D36D \le 36.

Subtasks

Subtask 1 (20 points): N10N \le 10

Subtask 2 (20 points): N1000N \le 1000, D10D \le 10

Subtask 3 (20 points): D18D \le 18

Subtask 4 (20 points): N=37N = 37, and all roads connect to one city, i.e. this city has 36 connected cities, and each of those cities is connected to it by only one road.

Subtask 5 (20 points): No additional constraints.

Translated by ChatGPT 5