酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

有一个由n个字符组成的字符串s,其中s仅由1或者0组成。你可以选择长度为k的片段,将其全部变成1,求最少操作多少次可以使s中没有连续大于等于m个0 **输入** 第一行包含一个整数 $t$ ( $1 \le t \le 10^4$ ),即测试用例的数量。 每个测试用例的第一行包含三个数字n,m,k。每个测试用例的第二行包含由 $n$ 个字符1或者0 组成的二进制字符串 s **输出** 针对每个测试案例,输出需要操作最少次数,确保没有长度为 $m$ 的0。 使用c++解决

首先,我们需要找到所有连续的0的片段,并记录它们的长度。 然后,我们可以遍历这些片段,对于每个长度大于等于m的片段,我们将其分成若干长度为k的子片段,并将它们全部变成1。操作的次数就是子片段的个数。 下面是一个示例的C++代码实现: ```cpp #include <iostream> #include <vector> #include <string> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m, k; cin >> n >> m >> k; string s; cin >> s; int count = 0; vector<int> lengths; // 保存所有连续的0片段的长度 int currLength = 0; for (int i = 0; i < n; i++) { if (s[i] == '0') { currLength++; } else { if (currLength > 0) { lengths.push_back(currLength); count += currLength / k; } currLength = 0; } } if (currLength > 0) { lengths.push_back(currLength); count += currLength / k; } // 处理长度大于等于m的片段 for (int i = 0; i < lengths.size(); i++) { if (lengths[i] >= m) { count -= lengths[i] / k; } } cout << count << endl; } return 0; } ``` 希望可以帮助到你! [2024-11-30 23:07:54 | AI写代码神器 | 876点数解答]

相关提问