Test instructions
Give a string of length n, with only the characters ' a ' and ' B '. A maximum of K characters can be changed, that is, ' a ' becomes ' B ' or ' B ' becomes ' a '.
Ask the length of the string with the longest consecutive same character after the change.
First of all, two-point search, good to write
1 varSArray[0..100000] ofLongint;2 ch:ansistring;3 N,k,i,l,r,mid,last,ans:longint;4 5 functionMax (x,y:longint): Longint;6 begin7 ifX>y Thenexit (x);8 exit (y);9 End;Ten One begin AAssign (input,'1.in'); Reset (input); -Assign (output,'1.out'); Rewrite (output); - readln (n,k); the READLN (CH); - fori:=1 toN Do - begin -s[i]:=s[i-1]; + ifch[i]='b' ThenInc (S[i]); - End; +ans:=0; A fori:=1 toN Do at begin -L:=i; R:=n; last:=i; - whileL<=r Do - begin -mid:= (l+r) >>1; - ifs[mid]-s[i-1]<=k Then beginLast:=mid; L:=mid+1;End in Elser:=mid-1; - End; toAns:=max (ans,last-i+1); + End; -Fillchar (s,sizeof (s),0); the fori:=1 toN Do * begin $s[i]:=s[i-1];Panax Notoginseng ifch[i]='a' ThenInc (S[i]); - End; the fori:=1 toN Do + begin AL:=i; R:=n; last:=i; the whileL<=r Do + begin -mid:= (l+r) >>1; $ ifs[mid]-s[i-1]<=k Then beginLast:=mid; L:=mid+1;End $ Elser:=mid-1; - End; -Ans:=max (ans,last-i+1); the End; - writeln (ans);Wuyi//close (input); the//close (output); - End.
View Code
Then a linear scan, ACM called the Ruler method, the machine room big God called the extension of the head contraction tail
L +1 after the cycle is due to the beginning of the next continuous interval, and the current continuous between the letter and the next paragraph must be different (obviously to find the longest consecutive same sequence)
1 varch:ansistring;2 N,k,ans,r,l,i,t:longint;3 4 functionMax (x,y:longint): Longint;5 begin6 ifX>y Thenexit (x);7 exit (y);8 End;9 Ten begin OneAssign (input,'1.in'); Reset (input); AAssign (output,'1.out'); Rewrite (output); - readln (n,k); - READLN (CH); thel:=1; r:=1; t:=0; - fori:=1 toN Do - begin - ifch[i]='b' Then + begin - ifT<k Then beginInc (T); Inc (R);End + Else A begin at while(l<=n) and(ch[l]='a') DoInc (L); - Inc (L); - Inc (R); - End; - End - ElseInc (R); inAns:=max (ans,r-l); - End; tol:=1; r:=1; t:=0; + fori:=1 toN Do - begin the ifch[i]='a' Then * begin $ ifT<k Then beginInc (T); Inc (R);EndPanax Notoginseng Else - begin the while(l<=n) and(ch[l]='b') DoInc (L); + Inc (L); A Inc (R); the End; + End - ElseInc (R); $Ans:=max (ans,r-l); $ End; - writeln (ans); -//close (input); the//close (output); - End.
View Code
"CF676C" Vasya and String (binary lookup, linear scan ruler)