题目描述
链接
6.26CF模拟赛D题
文字描述
D. 黑白条 time limit per test2 s. memory limit per test256 MB inputstandard input outputstandard output You have a stripe of checkered paper of length n. Each cell is either white or black.
你有一条长度为 n 的方格纸。每个方格被染上白色或者黑色。
What is the minimum number of cells that must be recolored from white to black in order to have a segment of k consecutive black cells on the stripe?
如果我们想在这条方格纸上得到一段连续 k 个黑格子,我们至少要把几个白格子重新染成黑格子?
If the input data is such that a segment of k consecutive black cells already exists, then print 0. 如果这条方格纸上已经存在一段连续 k 个黑格子,输出 0。
Input The first line contains an integer t (1≤t≤104) — the number of test cases.
第一行包含一个整数 t (1≤t≤104) — 代表测试数据组数。
Next, descriptions of t test cases follow.
以下是 t 组测试数据。
The first line of the input contains two integers n and k (1≤k≤n≤2?105). The second line consists of the letters ‘W’ (white) and ‘B’ (black). The line length is n.
第一行包含两个整数 n 和 k (1≤k≤n≤2?105)。第二行包含 n 个字母 ‘W’ (白) 和 ‘B’ (黑)。
It is guaranteed that the sum of values n does not exceed 2?105.
数据保证 n 之和不超过 2?10^5。
Output For each of t test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of k consecutive black cells.
每组测试数据输出一个整数代表答案。
Example inputCopy 4 5 3 BBWBW 5 5 BBWBW 5 1 BBWBW 1 1 W outputCopy 1 2 0 1 Note In the first test case, s=“BBWBW” and k=3. It is enough to recolor s3 and get s=“BBBBW”. This string contains a segment of length k=3 consisting of the letters ‘B’.
对于第一组样例,s=“BBWBW” 及 k=3,只将 s3 染黑即可得到 s=“BBBBW”。这个字符串包含连续 k=3 个 ‘B’。
In the second test case of the example s=“BBWBW” and k=5. It is enough to recolor s3 and s5 and get s=“BBBBB”. This string contains a segment of length k=5 consisting of the letters ‘B’. 对于第二组样例 s=“BBWBW” 及 k=5,需要将 s3 和 s5 得到 s=“BBBBB”。结果包含 k=5 个 ‘B’。
In the third test case of the example s=“BBWBW” and k=1. The string s already contains a segment of length k=1 consisting of the letters ‘B’.
对于第三组样例,s 已经满足要求。
题目分析
- 要使k个B连续所有可能的情况有n-k+1种(从首位1到n-k+1)
- 我们只需要知道这n-k+1种里有多少个W,取最小值就是最终的答案
- 有一种算法可以支持O(n)时间复杂度的算法,前缀和
- 第i位开头长度为k的字符串有f[i+k-1]-f[i-1]个W
代码实现
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
int t,n,k,ans;
char a[maxn];
int f[maxn];
int main(){
scanf("%d",&t);
while(t--){
ans=maxn;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++){
scanf(" %c",&a[i]);
f[i]=f[i-1];
if(a[i]=='W')f[i]++;
}
for(int i=1;i<=n-k+1;i++){
int x=f[i+k-1]-f[i-1];
ans=min(ans,x);
}
printf("%d\n",ans);
}
return 0;
}
|