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 …”.
题意:更改最小的次数使得s是 "RGBRGBRGB…"的子串
思路 :dp思想, a[3][j] ,3代表3种基本的串RGB, GBR, BRG,a[i][j]代表s串在以第i种基本串的无限连接形成的串在位置j下需要修改的次数, 再通过前缀和跑一遍就可以得ans;
代码:
/*************************************************************************
> File Name: cf575.cpp
> Author: Hcacai
> Created Time: 2019年07月24日 星期三 22时35分01秒
************************************************************************/
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
typedef long long ll;
const int N=2e5+10;
const int inf=0x3f3f3f3f;
char s[N];
int a[3][N];
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n, k;
scanf("%d%d%s", &n, &k, s);
string t="RGB";
for(int i=0; i<=2; i++)
{
for(int j=0; j<n; j++)
{
if(s[j]!=t[(i+j)%3]) a[i][j+1]=a[i][j]+1; //当i=0, 就是第一种基本串
else a[i][j+1]=a[i][j];
}
}
int ans=inf;
for(int i=0; i<=2; i++)
{
for(int j=0; j+k<=n; j++)
{
ans=min(a[i][j+k]-a[i][j],ans);
}
}
printf("%d\n", ans);
}
return 0;