atcoder#AGC059A. [AGC059A] My Last ABC Problem

[AGC059A] My Last ABC Problem

Score : 500500 points

Problem Statement

Consider a string tt consisting only of characters A, B, and C. We can do the following operation with it:

  • Choose any substring t[l:r]t[l:r] and any permutation (X,Y,Z)(X, Y, Z) of characters ((A,,B,,C)). Here, t[l:r]t[l:r] denotes the substring formed by the ll-th through the rr-th characters of tt, where ll and rr are of your choice. Then, replace each character A, B, and C in t[l:r]t[l:r] by XX, YY, and ZZ, respectively.

For example, for a string t=t = ACBAAC, we can choose a substring t[3:6]t[3:6] and (X,Y,Z)=((X,Y,Z)=(C,,B,,A)). After this operation, the string will become ACBCCA.

Alina likes strings in which all characters are the same. She defines the beauty of a string tt as the minimum number of operations required to make all its characters equal.

You are given a string SS of length NN consisting only of characters A, B, and C. Answer QQ queries. The ii-th query is the following:

  • Given integers LiL_i and RiR_i, find the beauty of the substring t=S[Li:Ri]t=S[L_i:R_i].

Constraints

  • 1N1051 \le N \le 10^5
  • SS is a string of length NN consisting only of characters A, B, and C.
  • 1Q1051 \le Q \le 10^5
  • 1LiRiN1 \le L_i \le R_i \le N
  • All numbers in the input are integers.

Input

Input is given from Standard Input in the following format:

NN QQ

SS

L1L_1 R1R_1

L2L_2 R2R_2

\vdots

LQL_Q RQR_Q

Output

Output QQ lines. In the ii-th line, output the answer to the ii-th query.

6 4
ABCCCA
3 5
2 3
1 3
1 6
0
1
2
2

In the first query, the string is t=t = CCC, in which all letters are already equal. The answer is 00.

In the second query, the string is t=t = BC. We can change it to BB in one operation, by choosing a substring t[2:2]t[2:2] and (X,Y,Z)=((X,Y,Z)=(A,,C,,B)).

In the third query, the string is t=t = ABC. We can change it to AAB in one operation, by choosing a substring t[2:3]t[2:3] and (X,Y,Z)=((X,Y,Z)=(C,,A,,B)), and then to BBB in the next operation, by choosing a substring t[1:2]t[1:2] and (X,Y,Z)=((X,Y,Z)=(B,,A,,C)).