欢迎来到起遇信息学
起遇信息学正处于上线筹建阶段,以下功能已全部开放免费体验: ✅ 完整题库浏览与代码提交评测(C / C++ / Python / Java 等) ✅ 入门到进阶的系列课程试读、作业与考试 ✅ AI 提示、AI 作业分析等智能助教功能 ✅ 赛事模拟与个人能力报告 ✅ 邮箱注册开放 ⏳ 付费课程订阅与微信/支付宝支付通道 ⏳ 手机号登录,微信扫码登录、微信公众号绑定 使用中如遇任何问题,欢迎通过页面底部 **"联系我们"** 与我们沟通。
CF2149D.A and B
A and B
Given a string of length , consisting only of the characters 'a' and 'b'.
In one operation, you can choose a position () and swap the neighboring characters and .
You need to perform the minimum number of operations to ensure that all characters of one type (either or ) are located strictly together, forming exactly one continuous block.
Characters of the other type can be positioned either before or after this block, forming two (possibly empty) blocks.
Examples of valid final forms:
- '
aaabbbaaa' — all 'b's are located together (one block), 'a's can be both before and after this block; - '
bbbaaaaaabbb' — all 'a's together, 'b's are at the edges of the string; - '
aaaaabbbb' or 'bbbbaaaaa' — both types of characters form one continuous block each.
You need to find the minimum number of described operations required to achieve the specified state.
Input
Each test consists of several test cases.
The first line contains one integer () — the number of test cases. The description of test cases follows.
The first line of each test case contains one integer () — the length of the string .
The second line contains the string of length , consisting only of the characters 'a' and 'b'.
It is guaranteed that the sum of the values of over all test cases does not exceed .
Output
For each test case, output one integer — the minimum number of operations required for all characters of one of the two types to form a single continuous block.
Note
In the first test case, the initial string is 'abab':
- by swapping the neighboring characters at positions and , we get the string '
aabb'; - or by swapping the characters at positions and , we get the string '
baab'.
In both cases, exactly one operation is performed, after which all letters of one type form a single block, so the minimum number of operations is .
In the fifth input test case, the string consists of a single character 'b'. The single character already forms a continuous block, no swaps are needed, so the minimum number of operations is .
Samples
5
4
abab
6
bababa
7
abababa
2
ab
1
b
1
2
2
0
0
在线编程 IDE
建议全屏模式获得最佳体验
| 进入全屏编程 | Alt+E |
| 递交评测 | Ctrl+Enter |
| 注释/取消注释 | Ctrl+/ |
| 缩放字体 | Ctrl+滚轮 |