Two SigmaOA #6
Sewer Drainage Partition
Estimated MediumJudge-ready
Topics (AI-labelled)Tree TraversalIn-place Arrays
The tree is rooted at 0, and each node has a direct inflow. Cut exactly one parent-child edge to split the tree into two parts, minimizing the absolute difference between the two parts' total direct inflow.
Input
The first line contains n, the second line contains n values of parent, and the third line contains n direct inflows. Complete original bounds: 2≤n≤100000, inflow 1..10000, parent[0]=−1, 0≤parent[i]<i, and the tree depth is at most 500.
Output
Output one integer answer.
Example 1
Input:
6
-1 0 0 1 1 2
1 2 2 1 1 1
Output:
0
Example 2
Input:
4
-1 0 1 2
1 4 3 4
Output:
2
Example 3
Input:
2
-1 0
10000 1
Output:
9999
Example notes
The outputs of the three public examples are, in order: 0; 2; 9999. They have been checked by independent enumeration or direct simulation.
Editorial
Loading solution…