练习cf1633B. Minority
题目如下
B. Minority
time limit per test2 seconds
memory limit per test256 megabytes
You are given a string 𝑠, consisting only of characters '0' and '1'.
You have to choose a contiguous substring of 𝑠 and remove all occurrences of the character, which is a strict minority in it, from the substring.
That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.
You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?
Input
The first line contains a single integer 𝑡 (1≤𝑡≤104) — the number of testcases.
The only line of each testcase contains a non-empty string 𝑠, consisting only of characters '0' and '1'. The length of 𝑠 doesn't exceed 2⋅105.
The total length of strings 𝑠 over all testcases doesn't exceed 2⋅105.
Output
For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.
题目大意
现有由1和0构成的串,选择其中,若子串中0的数量绝对大于1那么删除子串中所有的1,反之删除子串中所有的0;只能选择一个子串,最多能删除几个数。
题目分析
删除数最大的情况就是删除所有的0或1,此时子串就是这个串本身;若0和1的数量相等时,仍然是删除所有的0或1,此时只要让子串缩小一个单位,令1或0其中一个数量减少1即可。
点击查看代码
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin >> n;
while(n--){
string a;
cin >> a;
int cnt0 = 0, cnt1 = 0;
int cnt = 0;
for(char num : a){
if(num == '0'){
cnt0++;
}else{
cnt1++;
}
}
if(cnt0 == cnt1){
cnt = cnt0 - 1;
}else{
cnt = min(cnt0, cnt1);
}
cout << cnt << endl;
}
return 0;
}

浙公网安备 33010602011771号