#P10754. [COI 2023] Nestabilnost

[COI 2023] Nestabilnost

Background

Source: https://hsin.hr/hio2023/

Problem Description

The pine forest across the river, which was still bathed in May sunshine an hour ago, has now become blurry, hazy, and faded away. Only one huge tree remains, a tree with NN nodes...

Ivan is in room 119, observing this tree, which is firmly rooted at node 11. After looking at the tree more carefully, he notices that each node ii has a number aia_i on it. Suddenly, the definition of a kk-good subtree ("k-dobrog podstabla") flashes through his mind. If for every edge connecting nodes (u,v)(u, v) in a subtree (where uu is the parent of vv), we have av=(au+1)(modk)a_v = (a_u + 1) \pmod k, and for every node vv in that subtree, we have av<ka_v < k, then this subtree is kk-good. For each number kk, there is a natural instability of a kk-good subtree, denoted by f(k)f(k).

When he comes back to his senses, he notices a raft floating in front of the tree, and in his right hand he is holding a magic saw. Ivan decides to saw off some branches (edges). For each connected component (subtree) obtained by removing the sawed edges, he will choose a number kik_i such that this component is kik_i-good. Ivan decides to call such a set of choices—choosing a set of edges to cut, and choosing for each resulting subtree a valid kik_i (so that the subtree is kik_i-good)—a cutting ("rezanjem"). The instability ("Nestabilnost") of a cutting is defined as the sum of f(ki)f(k_i) over all resulting subtrees. Please help Ivan determine the minimum possible instability of a cutting!

Input Format

The first line contains a positive integer NN, the number of nodes in the tree.

The second line contains NN integers, where the ii-th number is aia_i (0aiN10 \le a_i \le N - 1).

The third line contains NN integers, where the kk-th number is f(k)f(k) (1f(k)1091 \le f(k) \le 10^9).

The next N1N - 1 lines describe the structure of the tree. The ii-th line contains two integers uiu_i and viv_i (1ui,viN,uivi1 \le u_i, v_i \le N, u_i \ne v_i), indicating that there is an edge between nodes uiu_i and viv_i.

Output Format

In the only line, output the minimum possible instability of a cutting.

7
2 3 0 3 2 0 0
6 8 2 9 9 9 9
1 2
2 3
1 4
4 5
5 6
5 7
11
7
2 3 0 3 2 0 0
6 8 2 9 9 9 1
1 2
2 3
1 4
4 5
5 6
5 7
4

Hint

[Sample Explanation]

The left picture is sample 1, and the right picture is sample 2.

[Constraints]

In all subtasks, 1N3×1051 \le N \le 3\times 10^5.

  • Subtask 1 (12 points): N5000N \leq 5 000, the tree is a chain, and node 11 is an endpoint of the chain.
  • Subtask 2 (20 points): N300000N \leq 300 000, the tree is a chain, and node 11 is an endpoint of the chain.
  • Subtask 3 (7 points): N20N \leq 20.
  • Subtask 4 (22 points): N5000N \leq 5000.
  • Subtask 5 (39 points): No additional constraints.

Translated by ChatGPT 5