题目链接在这里:Problem - B - Codeforces
尺取法一般用于一个数列中的连续子列的问题,思路有点类似于莫队,是一个很巧妙的算法
1 #include "bits/stdc++.h" 2 using namespace std; 3 const int MAX=1e5+5; 4 int n,k,ans; 5 char s[MAX]; 6 int main(){ 7 freopen ("b.in","r",stdin); 8 freopen ("b.out","w",stdout); 9 int i,j; 10 scanf("%d%d %s",&n,&k,s+1); 11 int low,high,le1,le2; 12 low=high=1;le1=le2=0;ans=0; 13 while (low<=high && high<=n){ 14 if (s[high]=='b'){ 15 le2++; 16 if (le2>k){ 17 while (s[low]=='a' && low<=high) low++; low++; 18 le2--; 19 } 20 } 21 ans=max(ans,high-low+1); 22 //cout<<low<<' '<<high<<' '<<ans<<endl; 23 high++; 24 } 25 low=high=1; 26 while (low<=high && high<=n){ 27 if (s[high]=='a'){ 28 le1++; 29 if (le1>k){ 30 while (s[low]=='b' && low<=high) low++; low++; 31 le1--; 32 } 33 } 34 ans=max(ans,high-low+1); 35 //cout<<low<<' '<<high<<' '<<ans<<endl; 36 high++; 37 } 38 39 printf("%d",ans); 40 return 0; 41 }