1. 程式人生 > 實用技巧 >Codeforces Round #575 (Div. 3) D2. RGB Substring (hard version)

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

題目連結:https://codeforces.ml/contest/1196/problem/D2

題意:由一個RGB無限重複構成的字串, 給定一個字串s 問最少更換多少個字母使得其中的一個長度為k的子串 是 RGB無限重複的字串的 子串

思路:因為只有3種可能的開頭其他都是重複的, 所以外層列舉 3 種不同的可能, 然後要o (n) 處理出結果, 考慮 處理的是子串 是一段連續的區間

要o (n) 處理的話不難想到用字首和維護, 值得注意的就是三種列舉的時候怎麼才最簡便

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define
ll long long 4 #define ull unsigned long long 5 const int maxn =2e5+10; 6 #define pb push_back 7 char t[10]={'R','G','B'}; 8 char s[maxn]; 9 int pre[maxn]; 10 11 int main() 12 { 13 ios::sync_with_stdio(false); 14 cin.tie(0); 15 int q; 16 cin>>q; 17 while(q--) 18 { 19
int n,k; 20 cin>>n>>k; 21 cin>>(s+1); 22 int ans=1e9; 23 for(int i=0;i<3;i++) 24 { 25 for(int j=1;j<=n;j++) 26 { 27 if(s[j]!=t[(i+j)%3]) 28 pre[j]=1; 29 else
30 pre[j]=0; 31 } 32 for(int j=1;j<=n;j++) 33 { 34 pre[j]+=pre[j-1]; 35 } 36 for(int j=k;j<=n;j++) 37 { 38 ans=min(ans,pre[j]-pre[j-k]); 39 } 40 } 41 42 cout<<ans<<'\n'; 43 } 44 45 46 47 48 49 50 }
View Code