CF1919B.Plus-Minus Split

传统题 时间 2000 ms 内存 256 MiB 3 尝试 1 已通过 1 标签

Plus-Minus Split

You are given a string ss of length nn consisting of characters "+" and "-". ss represents an array aa of length nn defined by ai=1a_i=1 if si=s_i= "+" and ai=1a_i=-1 if si=s_i= "-".

You will do the following process to calculate your penalty:

  1. Split aa into non-empty arrays b1,b2,,bkb_1,b_2,\ldots,b_k such that b1+b2++bk=ab_1+b_2+\ldots+b_k=a^\dagger, where ++ denotes array concatenation.
  2. The penalty of a single array is the absolute value of its sum multiplied by its length. In other words, for some array cc of length mm, its penalty is calculated as p(c)=c1+c2++cmmp(c)=|c_1+c_2+\ldots+c_m| \cdot m.
  3. The total penalty that you will receive is p(b1)+p(b2)++p(bk)p(b_1)+p(b_2)+\ldots+p(b_k).

If you perform the above process optimally, find the minimum possible penalty you will receive.

^\dagger Some valid ways to split a=[3,1,4,1,5]a=[3,1,4,1,5] into (b1,b2,,bk)(b_1,b_2,\ldots,b_k) are ([3],[1],[4],[1],[5])([3],[1],[4],[1],[5]), ([3,1],[4,1,5])([3,1],[4,1,5]) and ([3,1,4,1,5])([3,1,4,1,5]) while some invalid ways to split aa are ([3,1],[1,5])([3,1],[1,5]), ([3],[],[1,4],[1,5])([3],[\,],[1,4],[1,5]) and ([3,4],[5,1,1])([3,4],[5,1,1]).

Input

Each test contains multiple test cases. The first line contains a single integer tt (1t10001 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer nn (1n50001 \le n \le 5000) — the length of string ss.

The second line of each test case contains string ss (si{+,}s_i \in \{ \mathtt{+}, \mathtt{-} \}, s=n|s| = n).

Note that there are no constraints on the sum of nn over all test cases.

Output

For each test case, output a single integer representing the minimum possible penalty you will receive.

Note

In the first test case, we have a=[1]a=[1]. We can split array aa into ([1])([1]). Then, the sum of penalties of the subarrays is p([1])=1p([1]) = 1.

In the second test case, we have a=[1,1,1,1,1]a=[-1,-1,-1,-1,-1]. We can split array aa into ([1],[1],[1],[1],[1])([-1],[-1],[-1],[-1],[-1]). Then, the sum of penalties of the subarrays is $p([-1]) + p([-1]) + p([-1]) + p([-1]) + p([-1]) = 1 + 1 + 1 + 1 + 1 = 5$.

In the third test case, we have a=[1,1,1,1,1,1]a=[1,-1,1,-1,1,-1]. We can split array aa into ([1,1,1,1],[1,1])([1,-1,1,-1],[1,-1]). Then, the sum of penalties of the subarrays is p([1,1,1,1])+p([1,1])=0+0=0p([1,-1,1,-1]) + p([1,-1]) = 0 + 0 = 0.

Samples

5
1
+
5
-----
6
+-+-+-
10
--+++++++-
20
+---++++-+++++---++-
1
5
0
4
4

在线编程 IDE

建议全屏模式获得最佳体验