D2. RGB Substring (hard version) ( Codeforces Round #575 )

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 (1q21051≤q≤2⋅105) — the number of queries. Then qq queries follow.

The first line of the query contains two integers nn and kk (1kn21051≤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 21052⋅105 (n2105∑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 ...".

#include<bits/stdc++.h>
using namespace std;
 
const int maxn = 2e5+7;
int n,k;
string ori = "RGB";
string s;
int a[maxn],sum[maxn];
int solve(int st)
{
    for(int i=0; i<s.size(); i++)
    {
        a[i]=(s[i]==ori[(st+i)%3]?0:1);
        sum[i]=(i>0?a[i]+sum[i-1]:a[i]);
    }
    int res = s.size();
    for(int i=k-1; i<s.size(); i++)
    {
        res = min(res, sum[i]-(i-k>=0?sum[i-k]:0));
    }
    return res;
}
void solve()
{
    scanf("%d%d",&n,&k);
    cin>>s;
    int ans = s.size();
    for(int st=0; st<3; st++)
    {
        ans = min(ans, solve(st));
    }
    printf("%d\n", ans);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        solve();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Shallow-dream/p/11416735.html