#P7091. 数上的树
数上的树
Description
You need to construct a binary tree whose root node has value . Each node has either children or children, and it must satisfy the following rules:
- If a node has two children, then the node’s value must be equal to the product of its two children’s values.
- If a node has no children, then the node’s value must be a prime number.
You are also given constraints , meaning that the value must not appear anywhere in the tree.
Your constructed binary tree must minimize the following. Let be the number of nodes: $\sum\limits_{i=1}^k\sum\limits_{j=i}^kval_{lca(i,j)}$, where is the value of the -th node, and is the lowest common ancestor of nodes and .
Input Format
The first line contains two positive integers .
The next line contains numbers .
Output Format
Output one number in a single line, the minimum value of $\sum\limits_{i=1}^k\sum\limits_{j=i}^kval_{lca(i,j)}$.
If there is no solution, output -1.
4 0
20
12 1
4
127
192 1
2
-1
Hint
Sample explanation:
Sample : The optimal construction is as follows:

Here, black numbers are node values, and red numbers are node indices (you do not need to index the tree; these indices are only used to explain the sample more clearly).
$ans=val_{lca(1,1)}+val_{lca(1,2)}+val_{lca(1,3)}+val_{lca(2,2)}+val_{lca(2,3)}+val_{lca(3,3)}$
Subtask 1 (5 points): .
Subtask 2 (12 points): .
Subtask 3 (28 points): .
Subtask 4 (20 points): .
Subtask 5 (35 points): .
Constraints: for all testdata, , , , and the answer does not exceed .
Translated by ChatGPT 5
京公网安备 11011102002149号