#P8683. Maximizing Postfix Expression Result

    ID: 21849 Type: Default 1000ms 256MiB

Maximizing Postfix Expression Result

Maximizing Postfix Expression Result

You are given $N$ plus signs, $M$ minus signs, and $N+M+1$ integers $A_1, A_2, \cdots, A_{N+M+1}$.

You may arrange these numbers and operators to form a valid postfix (reverse Polish) expression. In a valid postfix expression, every operator acts on the two most recent values (operands) on the stack. For an expression composed of binary operators, the corresponding binary tree has exactly $N+M+1$ leaves (the numbers) and $N+M$ internal nodes (the operators).

Each plus operator $+$ adds its two operands, and each minus operator $-$ subtracts the second operand from the first. Through an appropriate binary tree structure, the evaluation can be understood in the following way: starting from the root with an implicit coefficient $+1$, each plus node keeps the coefficients of both children while a minus node keeps the coefficient of its left child but flips the sign of every leaf in its right subtree. Consequently, in any valid structure, exactly $M$ leaves will have a negative contribution and the remaining $N+1$ leaves will contribute positively.

To maximize the result of the expression, one should assign the negative signs to the smallest numbers and the positive signs to the largest numbers. More formally, if we sort the list $A_1, A_2,\cdots,A_{N+M+1}$ in increasing order as $a_1 \le a_2 \le \cdots \le a_{N+M+1}$, then the maximum result is given by:

[ \text{Result} = \left(\sum_{i=N+M+1-(N+1)+1}^{N+M+1} a_i\right) - \left(\sum_{i=1}^{M} a_i\right) = \left(\sum_{i=M+1}^{N+M+1} a_i\right) - \left(\sum_{i=1}^{M} a_i\right). ]

Your task is to compute and output this maximum result.

For example, given the input tokens 1 2 3 + - corresponding to $N=1$, $M=1$, and numbers 1, 2, 3, after sorting the numbers we have $1,2,3$. The optimal assignment is to use $2$ and $3$ as positive and $1$ as negative. The result is $(2+3)-1=4$, which is the maximum possible.

inputFormat

The first line contains two integers $N$ and $M$.

The second line contains $N+M+1$ integers representing $A_1, A_2, \cdots, A_{N+M+1}$, separated by spaces.

outputFormat

Output the maximum result that can be obtained from any valid postfix expression formed by the given numbers and operators.

sample

1 1
1 2 3
4