Loading

Codeforces Round #646 (Div. 2) B. Subsequence Hate(前缀和/思维)

Shubham has a binary string ss. A binary string is a string containing only characters "0" and "1".

He can perform the following operation on the string any amount of times:

  • Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.

A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.

What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.

A string aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.

Input

The first line of the input contains a single integer tt (1≤t≤100)(1≤t≤100) — the number of test cases.

Each of the next tt lines contains a binary string ss (1≤|s|≤1000)(1≤|s|≤1000).

Output

For every string, output the minimum number of operations required to make it good.

Example

Input

Copy

7

001

100

101

010

0

1

001100

Output

Copy

0

0

1

1

0

0

2

 

由于101和010比较特殊,导致最终二进制串可能的样子只能是000000001111111或者1111111000000这样(当然可以全为0或者1),这样预处理出到每个位置0的个数的前缀和,然后正反跑两趟枚举分界位置,利用前缀和计算代价更新答案即可。

#include <bits/stdc++.h>
using namespace std;
int sum[1005];//前缀和存0的个数 
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        s="0"+s;
        sum[0]=0;
        int n=s.size()-1,zero=0,one=0,i,ans=0x3f3f3f3f;
        for(i=1;i<=s.size()-1;i++)
        {
            if(s[i]=='0')
            {
                zero++;
                sum[i]=sum[i-1]+1;
            }
            else 
            {
                one++;
                sum[i]=sum[i-1];
            }
        }
        ans=min(one,zero);
        for(i=1;i<=n;i++)// 11111100000这样 枚举分界位置 
        {
            ans=min(ans,sum[i]+(n-i-(sum[n]-sum[i])));
        }
        for(i=1;i<=n;i++)// 0000011111这样 
        {
            ans=min(ans,i-sum[i]+sum[n]-sum[i]);
        }
        cout<<ans<<endl;
    }
}

 

posted @ 2020-06-01 10:48  脂环  阅读(499)  评论(0编辑  收藏  举报