RGB Substring (hard version)

原题:

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

The first line of the query contains two integers nn and kk (1≤k≤n≤2⋅1051≤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 2⋅1052⋅105 (∑n≤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 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 ...".

Input:

3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR

Out:

1
0
3

题意:通过删减任意字符串,使最后的子串由“RGBR……”,或“GBRGB……”或“BRGB……”,求删减的最少的次数。

答案要求的字符串一定由R,G,B之一开始,则三种枚举即可。

每一种都是一个长度为k的窗口,往后滑动,每次更新队尾,和减去最前面的队头造成的影响。

#include<bits/stdc++.h>
#define int long long
using namespace std;

const int N = 2e5 + 10;
int a[N],tot;
char r[4] = "RGB";
void add(){
	tot++;
	tot%=3;
}

int dp[N];

void sub(){
	tot--;
	tot %= 3;
}

signed main()
{
    int t; cin >> t;
    while(t--){
//    	memset(dp,0,sizeof dp);
//		由于的dp是从往前取值,因此不必全部置为0,不然会超时。 
		int n,k; cin >> n >> k;
		int ans = 1e9;
		string s; cin >> s;
		for(int i = 0;i < 3;i++){
			int cnt = 0;
			for(int j = 0;j < n;j++){
				dp[j] = s[j] != r[tot];
				cnt+=dp[j];
				add();
				if(j >= k){
					cnt -= dp[j - k];
				}
				if(j >= k - 1)
				ans = min(ans,cnt);
			}
		}
		
		cout << ans << endl;
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值