codeForces #575 div3 D - RGB Substring (easy 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≤2000) — the number of queries. Then q queries follow.
The first line of the query contains two integers n and k (1≤k≤n≤2000) — 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 2000 (∑n≤2000).
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”.

题目大意:给你一个长度为n的字符串,然后给你一个k,问你在这个长度为n的字符串中最少改变多少个字符可以让有k个连续的字符为"RGB"的循环。“RGBRGBRGB…”“GBRGBRGBR…”"BRGBRGBRG…"是这三种的其中一种的片段。
解题思路:可以直接将这三种情况全部遍历,开头为R,G,B这三种情况。如果不对就记录当前位置改变了一次,当前改变次数就+1。也就是一个前缀和数组。然后再次全部遍历,看从第j个开始往后k个,用第j+k个位置改变的次数减去第j个位置改变的次数,更新最小值,即为ans。

#include<iostream>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn=2e5+10;
char str[maxn];
int a[3][maxn];
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		string s="RGB";
		int n,k;
		cin>>n>>k>>str;
		for(int i=0;i<3;i++)		//将以GBR...   BRG...   RGB... 开头循环的全部遍历一次 
		{
			for(int j=0;j<n;j++)
			{
				if(str[j]!=s[(i+j)%3]) a[i][j+1]=a[i][j]+1;		//不相等的话下一个的值就等于当前的+1 即改变了一次 
				else a[i][j+1]=a[i][j];							//如果相等的话继续 
			}
		}
		int ans=INF;
		for(int i=0;i<3;i++)
		{
			for(int j=0;j+k<=n;j++)
			{
				ans=min(a[i][j+k]-a[i][j],ans);
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值