Codeforces Round #575 (Div. 3) D2. RGB Substring (hard version) 水题

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....的某个字串

题解

水题,枚举匹配位置,然后暴力匹配即可,然后再求长度为k的前缀和最小值

代码

#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;
}

转载于:https://www.cnblogs.com/qscqesze/p/11255580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值