原题:
You are given a string ss consisting of nn characters, each character is 'R', 'G' or 'B'.
You are also given an integer kk. Your task is to change the minimum number of characters in the initial string ss so that after the changes there will be a string of length kk that is a substring of ss, and is also a substring of the infinite string "RGBRGBRGB ...".
A string aa is a substring of string bb if there exists a positive integer ii such that a1=bia1=bi, a2=bi+1a2=bi+1, a3=bi+2a3=bi+2, ..., a|a|=bi+|a|−1a|a|=bi+|a|−1. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.
You have to answer qq independent queries.
Input
The first line of the input contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries. Then qq queries follow.
The first line of the query contains two integers nn and kk (1≤k≤n≤2⋅1051≤k≤n≤2⋅105) — the length of the string ss and the length of the substring.
The second line of the query contains a string ss consisting of nn characters 'R', 'G' and 'B'.
It is guaranteed that the sum of nn over all queries does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).
Output
For each query print one integer — the minimum number of characters you need to change in the initial string ss so that after changing there will be a substring of length kk in ss that is also a substring of the infinite string "RGBRGBRGB ...".
Input:
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
Out:
1
0
3
题意:通过删减任意字符串,使最后的子串由“RGBR……”,或“GBRGB……”或“BRGB……”,求删减的最少的次数。
答案要求的字符串一定由R,G,B之一开始,则三种枚举即可。
每一种都是一个长度为k的窗口,往后滑动,每次更新队尾,和减去最前面的队头造成的影响。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 10;
int a[N],tot;
char r[4] = "RGB";
void add(){
tot++;
tot%=3;
}
int dp[N];
void sub(){
tot--;
tot %= 3;
}
signed main()
{
int t; cin >> t;
while(t--){
// memset(dp,0,sizeof dp);
// 由于的dp是从往前取值,因此不必全部置为0,不然会超时。
int n,k; cin >> n >> k;
int ans = 1e9;
string s; cin >> s;
for(int i = 0;i < 3;i++){
int cnt = 0;
for(int j = 0;j < n;j++){
dp[j] = s[j] != r[tot];
cnt+=dp[j];
add();
if(j >= k){
cnt -= dp[j - k];
}
if(j >= k - 1)
ans = min(ans,cnt);
}
}
cout << ans << endl;
}
return 0;
}