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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!