#P2131. 彩球树
彩球树
Description
You are given a binary tree whose leaves have weights. Every internal node has exactly two children. Leaf weights are only or .
You can perform the following operation any number of times: choose two leaves and swap their weights.
Define the weight of a subtree as the sum of the weights of all leaves in that subtree.
You want to make the difference between the weights of the left and right subtrees at every internal node be at most by using the operation above.
Find the minimum number of operations needed to achieve this.
Input Format
One line containing a string that describes the tree in a fully parenthesized form. The character B denotes a colored ball.
Formally, the CFG (context-free grammar) of is defined as:
<T> := (<T><T>) | (B) | ()
| Item | Meaning |
|---|---|
(<T><T>) |
An internal node; the two <T> are its left and right subtrees. |
(B) |
A leaf node with weight . |
() |
A leaf node with weight . |
Output Format
Output a single integer: the minimum number of operations required, or output impossible if it is not achievable.
((B)())
0
((((B)(B))((B)()))(B))
impossible
(()(((B)(B))(B)))
1
Hint
Sample Explanation

Constraints
Let be the length of the string .
- For of the testdata, .
- For of the testdata, .
- For of the testdata, .
Translated by ChatGPT 5
京公网安备 11011102002149号