A String Puzzle
Time limit2sMemory limit1024 MB
For each substring, count the pointer moves needed to take every character so the answer comes out sorted, with the pointer wrapping around the string.
- Level
Hard8 of 10
- Topics
- String, Greedy, Sorting, Segment tree
- Solved
- No attempts yet
Statement
Jonathan knows many fun things from the big world. Today he gave Mavis the following problem. He probably knows it from some informatics olympiad, or maybe from somewhere else.
You have a string and a pointer that initially points to the first character. Two operations are available.
- Append the character at the current position to the end of the answer, provided that this position's character has not been taken before. Taking it leaves the original character in its position.
- Move the pointer one character to the right. If the current character is the last one, the pointer goes back to the first character of the string.
After some number of operations, all characters must be taken, and the characters of the answer string must be sorted in non-decreasing order.
For example, with the string hello, you can perform these operations:
- Second operation. Move the pointer to the character <<e>>.
- First operation. Take the character <<e>>.
- Second operation. Move the pointer to <<l>>.
- Second operation. The pointer is at <<l>>.
- Second operation. Move the pointer to <<o>>.
- Second operation. The pointer now points to the first character of the string, <<h>>.
- First operation. Take <<h>>. The answer string is <<eh>>.
- Second operation. The pointer is at <<e>>, which is already taken.
- Second operation.
- First operation. The answer is <<ehl>>.
- Second operation.
- First operation. The answer is <<ehll>>.
- Second operation.
- First operation. The answer is <<ehllo>>.
In total, there are operations of the first type and operations of the second type.
You need to solve a slightly modified version of this problem in the general case.
Input
The first line contains a string () made of lowercase Latin letters. The second line contains the number of queries (). Each of the next lines contains two integers and , the bounds of a query.
Output
For each query, print the number of second-type operations needed to solve the problem on the substring of from position to position , inclusive.