#P6513. [QkOI#R1] Quark and Tree
[QkOI#R1] Quark and Tree
Description
Given a tree with nodes, each node has a weight. The nodes are numbered from to . Please add one edge that does not exist in the given tree (and it must not be a self-loop), so that in the unicyclic graph formed after adding the edge, the sum of (depth of each node) times (its weight) is maximized.
We define the depth of a node in the unicyclic graph as the shortest distance from that node to the cycle. In particular, nodes on the cycle have depth .
Formally, you need to add an edge that does not exist in the given tree (and it must not be a self-loop), and maximize:
where is the weight of node , and is the depth of node in the unicyclic graph.
Input Format
The first line contains an integer , indicating the number of nodes in the tree.
The second line contains integers. The -th integer denotes the node weight of node .
The next lines each contain two integers , indicating that there is an edge between and in the tree.
Output Format
Output one integer in a single line, representing the maximum value of the sum of (each node’s depth) times (its weight) in the unicyclic graph after adding the edge.
7
1 1 1 1 1 1 1
1 2
1 3
2 5
3 4
3 7
4 6
8
5
-6 3 -1 -7 -2
1 2
1 3
3 4
5 1
3
Hint
Sample Explanation
The tree given in Sample 1 is shown in the figure below:

You can add the edge . The resulting unicyclic graph is shown below:

The depths of all nodes are shown in the table below:

Constraints
This problem uses bundled testdata.
For all testdata, , , .
- Subtask ( points): .
- Subtask ( points): .
- Subtask ( points): .
- Subtask ( points): no special constraints.
Translated by ChatGPT 5
京公网安备 11011102002149号