D2. RGB Substring (hard version)
传送门
he only difference between easy and hard versions is the size of the input.
You are given a string s consisting of n characters, each character is ‘R’, ‘G’ or ‘B’.
You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be a string of length k that is a substring of s, and is also a substring of the infinite string “RGBRGBRGB …”.
A string a is a substring of string b if there exists a positive integer i such that a 1 = b i , a 2 = b i + 1 , a 3 = b i + 2 , . . . , a ∣ a ∣ = b i + ∣ a ∣ − 1 a_1=b_i, a_2=b_i+1, a_3=b_i+2, ..., a_{|a|}=b_{i+|a|−1} a1=bi,a2=bi+1,a3=bi+2,...,a∣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 q independent queries.
Input
The first line of the input contains one integer q ( 1 ≤ q ≤ 2 ⋅ 1 0 5 1≤q≤2⋅10^5 1≤q≤2⋅105) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k ( 1 ≤ k ≤ n ≤ 2 ⋅ 1 0 5 1≤k≤n≤2⋅10^5 1≤k≤n≤2⋅105) — the length of the string s and the length of the substring.
The second line of the query contains a string s consisting of n characters ‘R’, ‘G’ and ‘B’.
It is guaranteed that the sum of n over all queries does not exceed 2 ⋅ 1 0 5 ( ∑ n ≤ 2 ⋅ 1 0 5 2⋅10^5 (∑n≤2⋅10^5 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 s so that after changing there will be a substring of length k in s that is also a substring of the infinite string “RGBRGBRGB …”.
Example
input
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
output
1
0
3
Note
In the first example, you can change the first character to ‘R’ and obtain the substring “RG”, or change the second character to ‘R’ and obtain “BR”, or change the third, fourth or fifth character to ‘B’ and obtain “GB”.
In the second example, the substring is “BRG”.
题目大意:
给你一串字符串让你做最小的修改,使得存在长度为k的子串,满足是 "RGBRGBRGB …"的子串
题目思路:
无论怎么变换都只有三种可能,即第一个为“R”,第一个为“G”,第一个为“B”,然后再往后修改。
所以我们记录当第一个为第一个为“R”,哪些字符串需要修改,哪些不需要,然后就可以记录到这个点有多少个已经符合的,然后只需第j个-(j-k)个取最小值即可。其他两种同理。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxd = 2e5+10;
char str[maxd];
const char s[4] = "RGB";
int pre[maxd];
int main()
{
int n,m,t,a,b,c;
scanf("%d",&t);
while(t--)
{
int ans=0;
scanf("%d %d",&n,&m);
scanf("%s",str+1);
for(int k=0;k<3;k++)
{
for(int i=1;i<=n;i++)
{
if(str[i]==s[(i+k)%3]) pre[i]=1; //判断是否符合
else pre[i]=0;
}
for(int j=1;j<=n;j++)pre[j]+=pre[j-1]; //计算符合的前缀和
for(int j=m;j<=n;j++) ans=max(ans,pre[j]-pre[j-m]); //前缀和相减,计算需要修改的
}
printf("%d\n",max(0,m-ans));
}
return 0;
}