本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来,并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构,旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。
欢迎大家订阅我的专栏:算法题解:C++与Python实现!
附上汇总贴:算法竞赛备考冲刺必刷题(C++) | 汇总
【题目来源】
洛谷:AT_abc379_b [ABC379B] Strawberries - 洛谷
【题目描述】
Takahashi has
N
N
N teeth arranged in a single row from left to right. The current condition of his teeth is represented by a string
S
S
S.
高桥的牙齿从左到右排成一列,共有
N
N
N 颗。他牙齿的当前状态用一个字符串
S
S
S 表示。
If the
i
i
i-th character of
S
S
S is O
, it means that the
i
i
i-th tooth from the left is healthy. If it is X
, it means that the
i
i
i-th tooth has a cavity. Healthy teeth do not have cavities.
若字符串
S
S
S 的第
i
i
i 个字符是 O
,表示从左数第
i
i
i 颗牙齿是健康的;若是 X
,则表示该牙齿有蛀牙。健康的牙齿不会有蛀牙。
When he has
K
K
K consecutive healthy teeth, he can eat one strawberry using those
K
K
K teeth. After eating a strawberry, those
K
K
K teeth develop cavities and become unhealthy.
当高桥有连续
K
K
K 颗健康牙齿时,他可以用这些牙齿吃一颗草莓。吃完草莓后,这
K
K
K 颗牙齿会形成蛀牙,变得不健康。
Find the maximum number of strawberries he can eat.
求解他最多可以吃多少颗草莓。
【输入】
The input is given from Standard Input in the following format:
N K
S
【输出】
Print the answer.
【输入样例】
7 3
OOXOOOO
【输出样例】
1
【算法标签】
《洛谷 AT_abc379_b Stawberries》 #模拟# #字符串#
【代码详解】
#include <bits/stdc++.h> // 包含标准库头文件
using namespace std; // 使用标准命名空间
// 全局变量:
// n: 字符串长度
// k: 需要统计的连续'O'的数量
// cnt: 当前连续'O'的计数器
// ans: 满足条件的连续'O'序列数量
// s: 输入的字符串
int n, k, cnt, ans;
string s;
int main()
{
// 输入字符串长度n和需要统计的连续'O'数量k
cin >> n >> k;
// 输入字符串s
cin >> s;
// 在字符串前添加空格,使索引从1开始
s = " " + s;
// 遍历字符串中的每个字符
for (int i = 1; i <= n; i++)
{
// 当前字符是'O'
if (s[i] == 'O')
{
cnt++; // 增加连续'O'计数器
// 如果达到k个连续'O'
if (cnt == k)
{
ans++; // 增加满足条件的序列计数
cnt = 0; // 重置计数器
}
}
// 当前字符不是'O'
else
{
cnt = 0; // 重置连续'O'计数器
}
}
// 输出满足条件的连续'O'序列数量
cout << ans << endl;
return 0; // 程序正常结束
}
【运行结果】
7 3
OOXOOOO
1