Play Games with Rounddog
Time limit5sMemory limit512 MB
For each query substring T, find the largest total stone count of Calabash's piles such that he wins Nim no matter which piles Rounddog removes, or -1.
- Level
Hard9 of 10
- Topics
- String, String matching, Bit manipulation, Tree
- Solved
- No attempts yet
Problem
Nim is a stone-picking game known around the world for its simple rules. At the start, there are several piles of stones. Two players take turns removing at least one stone from one of the piles. A player who cannot make a legal move loses.
On August 17th, a very special day, Rounddog and Calabash create a stone-picking game of their own. The new rules are as follows.
At the start, Calabash takes a string out of his right pocket. It is the keystone of their game, which has rounds in total.
At the beginning of each round, their common friend Severus selects a substring of . Before the players start, there are three preparation phases.
In Phase 1, Calabash selects one or more distinct substrings of that all have as a suffix. For example, "ris" is a suffix of "claris". A string is a suffix of itself.
In Phase 2, Calabash turns every string he selected into a pile. For each selected string , the pile has stones, where is the number of occurrences of in . For example, "aba" occurs twice in "ababa", so it becomes a pile of two stones.
In Phase 3, Rounddog acts after Severus and Calabash have made their moves. Rounddog chooses some of Calabash's piles and throws them away. Rounddog cannot throw away all of the piles, because then the game would end immediately.
The remaining piles are played as the classic Nim game. Calabash moves first.
Quailty wants to know whether Calabash wins in each round if both players play optimally. He also wants the maximum total number of stones Calabash can create in Phase 2 such that he still wins with optimal play.
Input
The first line contains a single integer (), the number of test cases.
Each test case starts with an integer ().
The second line contains a string of length made of lowercase English letters.
The third line contains integers ().
The next line contains an integer (), the number of rounds.
Each of the next lines contains two integers and (), meaning that in this round Severus selects as .
Output
For each test case, print lines, one per round. Each line contains the maximum total number of stones Calabash can create in Phase 2 of that round so that he still wins with optimal play. If he always loses, print .