Under construction

Still being built. Things may change

String Folding (Hard)

Time limit1.5sMemory limit1024 MB

Summary
Given a string and many queries (l, r), find the maximum number of equal-letter pairs that touch when the substring S[l..r] is folded once between two adjacent characters.
Level

Medium6 of 10

Topics
String, Prefix sum, Dynamic programming
Solved
No attempts yet

Problem

A long strip of paper has a string of uppercase English letters written on it in a single line. For example, suppose the paper has “ABAACA” written on it, as shown in the figure below.

You fold this paper exactly once. The paper can only be folded between two adjacent characters. For example, you can fold the paper between the 4th and 5th characters, as shown below.

Among the pairs of characters that touch after folding, the number of pairs with the same character is the score of that fold. For example, the score of the fold above is 11. However, folding the paper between the 3rd and 4th characters, as shown below, gives a score of 22.

You are given a string SS of uppercase letters, and you must answer QQ queries of the following form.

  • l rl \ r: If the llth character, the (l+1)(l+1)th character, ⋯\cdots, the rrth character are written on the paper in that order, what is the maximum score you can get by folding the paper once?

Input

The first line contains the integer NN, the length of the string.

The second line contains the string SS, which consists only of uppercase English letters.

The third line contains the integer QQ.

From the fourth line onward, the next QQ lines each contain two integers ll and rr, separated by a space, describing one query.

Output

For each query, print the answer on its own line, in order.

Constraints

  • 2≤N≤5,0002 \le N \le 5{,}000
  • 1≤Q≤200,0001 \le Q \le 200{,}000
  • 1≤l<r≤N1 \le l \lt r \le N

Examples2

  1. Example 1

    Input
    6
    ABAACA
    4
    1 4
    2 5
    3 6
    1 6
    
    Expected output
    1
    1
    1
    2
    
  2. Example 2

    Input
    5
    ABBAB
    4
    1 5
    1 4
    2 5
    3 5
    
    Expected output
    2
    2
    1
    0