#P1040. [NOIP 2003 提高组] 加分二叉树

    ID: 40 远端评测题 1000ms 128MiB 尝试: 1 已通过: 1 难度: 6 上传者: 标签>动态规划,dp2003递归NOIp 提高组Special JudgeO2优化枚举,暴力

[NOIP 2003 提高组] 加分二叉树

Description

Let a binary tree tree\text{tree} with nn nodes have an inorder traversal of (1,2,3,,n)(1, 2, 3, \ldots, n), where 1,2,3,,n1, 2, 3, \ldots, n are the node indices. Each node has a positive integer score; denote the score of node ii as did_i. The tree and each of its subtrees have a score. For any subtree subtree\text{subtree} (including tree\text{tree} itself), its score is computed as follows:

score of the left subtree of subtree\text{subtree} ×\times score of the right subtree of subtree\text{subtree} ++ score of the root of subtree\text{subtree}.

If a subtree is empty, its score is defined as 11. The score of a leaf equals the score of the leaf node itself; its empty children are not considered.

Find a binary tree tree\text{tree} whose inorder traversal is (1,2,3,,n)(1, 2, 3, \ldots, n) and whose score is maximized. Output:

  1. The maximum score of tree\text{tree}.
  2. The preorder traversal of tree\text{tree}.

Input Format

The first line contains one integer nn, the number of nodes.

The second line contains nn space-separated integers, the score of each node.

Output Format

The first line contains one integer, the maximum score (Ans4,000,000,000Ans \le 4,000,000,000).

The second line contains nn space-separated integers, the preorder traversal of the tree.

5
5 7 1 2 10

145
3 1 2 4 5

Hint

Constraints

For all testdata, it is guaranteed that 1n<301 \le n < 30, each node’s score is a positive integer less than 100100, and the answer does not exceed 4×1094 \times 10^9.

Translated by ChatGPT 5