#P2131. 彩球树

彩球树

Description

You are given a binary tree whose leaves have weights. Every internal node has exactly two children. Leaf weights are only 00 or 11.

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 11 by using the operation above.

Find the minimum number of operations needed to achieve this.

Input Format

One line containing a string TT that describes the tree in a fully parenthesized form. The character B denotes a colored ball.


Formally, the CFG (context-free grammar) of TT 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 11.
() A leaf node with weight 00.

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 NN be the length of the string TT.

  • For 15%15\% of the testdata, N25N \le 25.
  • For 50%50\% of the testdata, N250N \le 250.
  • For 100%100\% of the testdata, 2N50002 \le N \le 5000.

Translated by ChatGPT 5