链接:https://codeforces.com/contest/1196/problem/D2
The only difference between easy and hard versions is the size of the input.
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 ...".
Example
input
Copy
3 5 2 BGGGG 5 3 RBRGR 5 5 BBBRR
output
Copy
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".
代码:
#include <bits/stdc++.h>
using namespace std;
char x[1000001];
char a[10];
char b[10];
char c[10];
long long t,n,k,s1,s2,s3,min1;
int main()
{
cin>>t;
a[0]='R';
a[1]='G';
a[2]='B';
b[1]='R';
b[2]='G';
b[0]='B';
c[2]='R';
c[0]='G';
c[1]='B';
while(t--)
{
cin>>n>>k;
cin>>x;
s1=0,s2=0,s3=0;
for(int i=0;i<k;i++)
{
if(x[i]!=a[i%3])
s1++;
if(x[i]!=b[i%3])
s2++;
if(x[i]!=c[i%3])
s3++;
}
min1=min(s1,s2);
min1=min(min1,s3);
for(int i=k,j=0;i<n;i++,j++)
{
if(x[i]!=a[i%3])
s1++;
if(x[i]!=b[i%3])
s2++;
if(x[i]!=c[i%3])
s3++;
if(x[j]!=a[j%3])
s1--;
if(x[j]!=b[j%3])
s2--;
if(x[j]!=c[j%3])
s3--;
min1=min(min1,s1);
min1=min(min1,s2);
min1=min(min1,s3);
}
cout<<min1<<endl;
}
}