Under construction

Still being built. Things may change

Making a Good Binary String

Time limit2sMemory limit1024 MB

Summary
Given a binary string, find the fewest character flips so that the shortest intervals covering all 0s and all 1s have equal length.
Level

Hard8 of 10

Topics
Prefix sum, Dynamic programming, Math
Solved
No attempts yet

Problem

A binary string a_1a_2...a_na\_1a\_2...a\_n of length nn made of 00 and 11 is given. For a cost of 11, you can change one character into the other character.

A good binary string is a string that satisfies all of the following conditions.

  • It contains at least one 00 and at least one 11.
  • The minimum length of an interval containing all 00s is equal to the minimum length of an interval containing all 11s. An interval [ss, ee] contains jj if every ii with ai=ja_i=j satisfies s≤i≤es \leq i \leq e (1≤i≤n1 \leq i \leq n, j=0j=0, 11). The length of an interval [ss, ee] is defined as e−se-s.

Find the minimum cost to turn the given string into a good binary string.

Input

The first line contains the number of test cases TT (1≤T≤1031 \leq T \leq 10^3).

Each test case consists of the following.

The first line contains the length of the binary string nn (1≤n≤1061 \leq n \leq 10^6).

The next line contains a string of length nn made of 00 and 11.

It is guaranteed that the sum of nn over all test cases is at most 10610^6.

Output

For each test case, print −1-1 if the given string cannot be turned into a good binary string. Otherwise, print the minimum cost to turn it into a good binary string.

Examples1

  1. Example 1

    Input
    3
    6
    100100
    5
    10010
    1
    0
    
    Expected output
    1
    0
    -1