qscqesze
Published on 2017-09-02 11:31 in 暂未分类 with qscqesze

# D2. RGB Substring (hard version)

inputstandard input
outputstandard output
The only difference between easy and hard versions is the size of the input.

You are given a string 𝑠 consisting of 𝑛 characters, each character is 'R', 'G' or 'B'.

You are also given an integer 𝑘. Your task is to change the minimum number of characters in the initial string 𝑠 so that after the changes there will be a string of length 𝑘 that is a substring of 𝑠, and is also a substring of the infinite string "RGBRGBRGB ...".

A string 𝑎 is a substring of string 𝑏 if there exists a positive integer 𝑖 such that 𝑎1=𝑏𝑖, 𝑎2=𝑏𝑖+1, 𝑎3=𝑏𝑖+2, ..., 𝑎|𝑎|=𝑏𝑖+|𝑎|−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 𝑞 independent queries.

## Input

The first line of the input contains one integer 𝑞 (1≤𝑞≤2⋅105) — the number of queries. Then 𝑞 queries follow.

The first line of the query contains two integers 𝑛 and 𝑘 (1≤𝑘≤𝑛≤2⋅105) — the length of the string 𝑠 and the length of the substring.

The second line of the query contains a string 𝑠 consisting of 𝑛 characters 'R', 'G' and 'B'.

It is guaranteed that the sum of 𝑛 over all queries does not exceed 2⋅105 (∑𝑛≤2⋅105).

## Output

For each query print one integer — the minimum number of characters you need to change in the initial string 𝑠 so that after changing there will be a substring of length 𝑘 in 𝑠 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".

## 题目大意

q次询问，每次询问给你一个n个长度的字符串和长度k，要求你在n长度的字符串里面找到一个长度为k的子串，使得修改最少为RGBRGB....的某个字串

## 代码

#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;
}
posted @ 2019-07-27 16:21  qscqesze  阅读(239)  评论(0编辑  收藏