This page is still under construction.

Parts of this page are still being built. What you see may change.

Switch Array

Time limit1sMemory limit256 MB

Summary
Find the fewest restricted toggles that turn each given bit string into all zeros.
Level

Medium7 of 10

Topics
Recursion, Dynamic programming, Math
Solved
No attempts yet

Problem

A new locking device has been built.

The device consists of switches s1,s2,…,sNs_1, s_2, \ldots, s_N, each of which is either open or closed. The state of a switch is 0 or 1, so the state of the device is an array of NN bits.

The table below shows an example array with 8 switches.

switchs1s_1s2s_2s3s_3s4s_4s5s_5s6s_6s7s_7s8s_8
state01101100

In an array of NN switches, the rules for operating a switch are as follows.

  • Rule 1) You can toggle sNs_N at any time to change its state.
  • Rule 2) When si+1s_{i+1} is 1 and si+2,si+3,…,sN−1,sNs_{i+2}, s_{i+3}, \ldots, s_{N-1}, s_N are all 0, you can toggle sis_i to change its state. This rule also applies when the switches si+2,si+3,…,sN−1,sNs_{i+2}, s_{i+3}, \ldots, s_{N-1}, s_N do not exist at all. For example, you can toggle sN−1s_{N-1} as long as sNs_N is 1.
  • Rule 3) You can toggle only one switch at a time.

The device opens when every switch is 0.

Following the rules above, find the minimum number of toggles that turns the given array into all zeros.

The table below is a shortest sequence that turns the array 1111 into 0000. The array 1111 needs at least 10 toggles.

toggless1s_1s2s_2s3s_3s4s_4
01111
11101
21100
30100
40101
50111
60110
70010
80011
90001
100000

Input

The first line contains the number of test cases TT.

Each test case follows on its own line as a bit string BB. The first bit of BB is s1s_1 and the last bit is sNs_N.

The length of BB satisfies 2≤∣B∣≤312 \le |B| \le 31.

Output

For each test case, print on one line the minimum number of toggles needed to turn every switch to 0.

Examples4

  1. Example 1

    Input
    5
    1111
    11111
    1010101010
    000
    000000010
    
    Expected output
    10
    21
    819
    0
    3
    
  2. Example 2

    Input
    4
    00
    01
    10
    11
    
    Expected output
    0
    1
    3
    2
    
  3. Example 3

    Input
    3
    00
    0000000000
    0000000000000000000000000000000
    
    Expected output
    0
    0
    0
    
  4. Example 4

    Input
    8
    10000000
    01000000
    00100000
    00010000
    00001000
    00000100
    00000010
    00000001
    
    Expected output
    255
    127
    63
    31
    15
    7
    3
    1