http://codeforces.com/problemset/problem/1196/D2
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”.
题目大意:给定一个字符串,你可以任意修改其中的元素,使其有一个长度为
k
k
k的子串且这个子串也是
S
S
S的子串。其中
S
S
S是一个无限长的"RGB"的循环。
思路:暴力容易想到枚举子串的开始位置,但是这样的复杂度是
O
(
n
∗
k
)
O(n*k)
O(n∗k)的,但是借助前缀和我们可以
O
(
n
)
O(n)
O(n)枚举子串。以字符串"RGBGB"为例,根据每一位的贡献不难得到序列:
0
,
0
,
0
,
1
,
1
0,0,0,1,1
0,0,0,1,1,那么可得到前缀和:
0
,
0
,
0
,
1
,
2
0,0,0,1,2
0,0,0,1,2,从
i
=
k
i=k
i=k起始枚举到
n
n
n计算
s
u
m
[
i
]
−
s
u
m
[
i
−
k
]
sum[i]-sum[i-k]
sum[i]−sum[i−k]易得三个子串的贡献分别为:
0
,
1
,
2
0,1,2
0,1,2,我们肯定要取最小的那一个。注意到
S
S
S的子串有三种:
R
G
B
,
G
B
R
,
B
R
G
RGB,GBR,BRG
RGB,GBR,BRG,因此我们算三次就行了。
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cstring>
#define pr pair<int,int>
#define INF 1e5
using namespace std;
int m,n,k;
int sum[3][200005];
char s1[3][5]={"0RGB","0GBR","0BRG"};
char s2[200005];
int main()
{
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&n,&k);
scanf("%s",s2+1);
int tmp;
for(int i=0;i<3;i++)
{
for(int j=1;j<=n;j++)
{
tmp=j%3;
if(!tmp)
tmp=3;
if(s2[j]==s1[i][tmp])
sum[i][j]=sum[i][j-1];
else
sum[i][j]=sum[i][j-1]+1;
}
}
int ans=1e9;
for(int i=0;i<3;i++)
for(int j=k;j<=n;j++)
ans=min(ans,sum[i][j]-sum[i][j-k]);
printf("%d\n",ans);
}
return 0;
}