Minority
题面翻译
- 给定一个 \(01\) 字符串 \(s\),定义 \(c_k(l,r)\) 表示 \(s\) 的由下标为 \([l,r]\) 中的字母构成的连续子串中 \(k\) 的个数。
- 定义 \(f(l,r)=\begin{cases}c_0(l,r)&c_0(l,r)<c_1(l,r)\\c_1(l,r)&c_0(l,r)>c_1(l,r)\\0&c_0(l,r)=c_1(l,r)\end{cases}\),求 \(\max\limits_{1\le l\le r\le n}f(l,r)\)。多组询问。
- \(T\le10^4,\sum|s|\le2\times10^5\)
题目描述
You are given a string $ s $ , consisting only of characters '0' and '1'.
You have to choose a contiguous substring of $ s $ 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?
输入格式
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) — the number of testcases.
The only line of each testcase contains a non-empty string $ s $ , consisting only of characters '0' and '1'. The length of $ s $ doesn't exceed $ 2 \cdot 10^5 $ .
The total length of strings $ s $ over all testcases doesn't exceed $ 2 \cdot 10^5 $ .
输出格式
For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.
样例 #1
样例输入 #1
4
01
1010101010111
00110001000
1
样例输出 #1
0
5
3
0
大致题意
在字符串中选出一个子串删除其中少的那个\(1\)或\(0\),问能够删除的\(1\)或\(0\)个数最多是多少。
解题思路
这里题意说是让我们选出一个子串,其实不然,我们直接看整个字符串,整个字符串中\(1\)和\(0\)的个数应当有\(3\)种情况。
- \(1\)或\(0\)的个数为零,其中之一为零那么删除的只能是为零的那个,结果也是零。
- \(1\)的个数大于\(0\),既然我们要求答案要删除最多的\(1\)或\(0\)的个数,那么我们直接选用整个字符串作为子串,删除其中的\(0\),而\(0\)的个数就是我们要找的答案。
- \(1\)的个数小于\(0\),思路和上面一样答案就是数量少的那一方。
- \(1\)的个数等于\(0\),这时候我们如果选择一整个字符串作为子串那么答案就是零,但是我们想想题目是让我们选一个子串,所以我们的思路不要局限在前面所说的将整个字符串作为子串,因为\(1\)和\(0\)个数相同那么我们只要将字符串最后那个\(1\)或\(0\)排除掉,选前面部分作为子串就构成了删除的条件。所以这种情况下答案就是\(1\)或\(0\)的个数减一。
AC代码
#include<iostream>
using namespace std;
const int N = 2e5 + 10;
char s[N];
int main()
{
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", s);
int one = 0, zero = 0;
for (int i = 0; s[i] != '\0'; i++) {
//记录0和1的个数
switch (s[i]) {
case '1': one++; break;
case '0': zero++; break;
}
}
//四种情况的判断,同时输出结果
if (one == 0 || zero == 0)
printf("0\n");
else if (one < zero)
printf("%d\n", one);
else if (zero < one)
printf("%d\n", zero);
else if (one == zero)
printf("%d\n", one - 1);
}
return 0;
}
标签:子串,CF1633B,le,题解,个数,amount,zero,字符串
From: https://www.cnblogs.com/XiaoWang-554/p/17971239