CF BUDDY
← Problems·

1059E · Split the Tree

2400 · binary search, data structures, dp

Problem: You are given a rooted tree on nn vertices, its root is the vertex number 11. The ii-th vertex contains a number wiw_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than LL vertices and the sum of integers wiw_i on each path does not exceed SS. Each vertex should belong to exactly one path.

A vertical path is a sequence of vertices v1,v2,,vkv_1, v_2, \ldots, v_k where viv_i (i2i \ge 2) is the parent of vi1v_{i - 1}.

Input Format: The first line contains three integers nn, LL, SS (1n1051 \le n \le 10^5, 1L1051 \le L \le 10^5, 1S10181 \le S \le 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path.

The second line contains nn integers w1,w2,,wnw_1, w_2, \ldots, w_n (1wi1091 \le w_i \le 10^9) — the numbers in the vertices of the tree.

The third line contains n1n - 1 integers p2,,pnp_2, \ldots, p_n (1pi<i1 \le p_i < i), where pip_i is the parent of the ii-th vertex in the tree.

Output Format: Output one number  — the minimum number of vertical paths. If it is impossible to split the tree, output 1-1.

Note: In the first sample the tree is split into {1}, {2}, {3}\{1\},\ \{2\},\ \{3\}.

In the second sample the tree is split into {1, 2}, {3}\{1,\ 2\},\ \{3\} or {1, 3}, {2}\{1,\ 3\},\ \{2\}.

In the third sample it is impossible to split the tree.

Sample Cases

Case 1

Input

3 1 3
1 2 3
1 1

Output

3

Case 2

Input

3 3 6
1 2 3
1 1

Output

2

Case 3

Input

1 1 10000
10001

Output

-1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback