Subsequence Hate

Subsequence Hate


来源:CodeForces - 1363B


题目描述:

Shubham has a binary string s. 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 a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.


输入格式:

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

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


输出格式:

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


输入样例:

7
001
100
101
010
0
1
001100

输出样例:

0
0
1
1
0
0
2

思路:

要满足题目条件,只需要让二进制串成为左边全是零右边全是一或者左边全是一右边全是零的串即可。

遍历字符串,统计每个位置之前1的个数。

而后遍历每个位置,统计当前位置以前全为0当前位置及以后全为1或者当前位置全为1当前位置及以后全为0所需要的操作数,取最小值即可得出答案。

统计当前位置以前全为0的操作数:即当前位置以前1的个数;

统计当前位置及以后全为1的操作数:即当前位置及以后0的个数,用当前位置及以后的数的总数减去当前位置及以后1的个数即可得出;

统计当前位置以前全为1的操作数:即当前位置以前0的个数,当前位置的下标表示当前位置以前还有多少个数,用当前位置的下标减去当前位置以前1的个数即可得出。

统计当前位置及以后全为0的操作数:即当前位置及以后1的个数,用总的1的个数减去当前位置以前1的个数即可得出。


AC代码:

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef unsigned long long ULL;

const int INF = 0x3f3f3f3f;

void init ()
{
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}

vector<int> sum;

int main ()
{

    init();

    int T;
    cin >> T;
    while (T--)
    {
        string s;
        cin >> s;
        int n = s.length();
        sum.resize(n + 1);
        for (int i = 0; i < n; i++)
            sum[i + 1] = sum[i] + s[i] - '0';
        int ans = n;
        for (int i = 0; i <= n; i++)
            ans = min({ans, sum[i] + n - i - (sum[n] - sum[i]), i - sum[i] + sum[n] - sum[i]});
        cout << ans << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值