RGB string(hard-version)


RGB string(hard-version)


The 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 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⋅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⋅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⋅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”.
当一个字母出现时它会有三种不同的“命运“” 按照序“RGB”or“GBR”or"BRG"这也会影响接下来字母的循序因为每一个字母都可以视为一个起始点并且是与上一个字母串联也就是说总的循序就三种根据循序更改字母然后就是dp了。在实践中我深刻铭记了runtime原因其一是数组越界 眼瞎

#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
#define N 1000000+5
#define NN 100000000
char run[4]="RGB",time[N];ll dp[3][N];
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        ll k,p,mm=NN;cin>>k>>p>>time+1;
        for(int i=1;i<=k;i++)
        {
            for(int y=0;y<3;y++)
            {
                if(time[i]==run[(i+y)%3])
                dp[y][i]=dp[y][i-1];
                else dp[y][i]=dp[y][i-1]+1;
                if(i>=p)mm=min(mm,dp[y][i]-dp[y][i-p]);
            }
        }
        cout<<mm<<endl;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值