Sort String

1.6

17 votes
, Algorithms, Greedy algorithm, Linear Search
Problem

 You are given a binary string S of length N. You can apply the following operation to the string S :

  • Choose two distinct indices i,j(1i,jN,ij) and flip the characters Si,Sj.

Find the minimum number of operations required to sort the given string S. It is always possible to sort any string under the given constraints.

 Input format

  • The first line contains T denoting the number of test cases. The description of T test cases is as follows:
  • For each test case:
    • The first line contains N denoting the length of string S.
    • The second line contains the binary string S.

Output format

For each test case, print the minimum number of operations required to sort the given string S.

Constraints

1T1051N3105Scontains0sand1s.SumofNoveralltestcasesdoesnotexceed3105.

 

Sample Input
2
3
101
6
110100
Sample Output
1
2
Time Limit: 10
Memory Limit: 256
Source Limit:
Explanation

In the first test case, choose i=1,j=3 and flip S1,S3 making S=111 which is a sorted string.

In the second test case, choose i=1,j=2 and flip S1,S3 making S=000100, then  choose i=5,j=6 and flip S5,S6 making S=000111, which is a sorted string.

Editor Image

?