【題目描述】
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≤2?105) — the number of queries. Then q
queries follow.
The first line of the query contains two integers n
and k (1≤k≤n≤2?105) — 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 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 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
BBBRROutput1
0
3
【題目分析】
題目要求給定串改變最少的字符使串的一個子串變成一個無限長串"RGBRGBRGB……""RGBRGBRGB……""RGBRGBRGB……"的一個子串
我自己看完后十分懵逼,因為沒什么想法,既沒有說改變的是哪一部分子串,也沒有說變成什么樣子,還需要最小。在看到別人的博客以后才恍然大悟,我們不必要將目光局限在改變的那一小部分子串上,我們如果將最終改變的子串拓展成和給定串長度相同的串,無外乎三種,分別以RRR、GGG、BBB開頭,我們就分別計算如果將串變成那三種樣子哪些位置需要改變(需要改變的位置記為1,不需要改變的位置記為0,然后用一個前綴和數組進行維護),然后再找長度為k的子串中需要改變最少的。
覺得自己這種抽象能力不太夠,還需要多進行鍛煉。
【AC代碼】
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<climits>
#include<cstdlib>
#include<cmath>using namespace std;typedef long long ll;const int MAXN=200005;
char s[MAXN];
const char t[4]="RGB";
int sum[MAXN][3];
int ans;int main()
{int T,n,k;scanf("%d",&T);while(T--){scanf("%d%d",&n,&k);scanf("%s",s);ans=INT_MAX;//memset(sum,0,sizeof(sum));sum[0][0]=sum[0][1]=sum[0][2]=0;for(int i=0;i<n;i++){for(int j=0;j<3;j++){if(s[i]!=t[(i+j)%3]){sum[i+1][j]=sum[i][j]+1;}else{sum[i+1][j]=sum[i][j];}}}for(int i=0;i<=n-k;i++){for(int j=0;j<3;j++){ans=min(ans,sum[i+k][j]-sum[i][j]);}}printf("%d\n",ans);}return 0;
}