Algorithm Speedup
Time limit8sMemory limit128 MB
Decide whether a recursively defined Boolean function F on two sequences returns 1 or 0, where F strips the longest prefix and suffix that drop some value.
- Level
Medium7 of 10
- Topics
- Recursion, Hash map, String matching, Implementation
- Solved
- No attempts yet
Problem
As a punishment for misbehaving, Byteasar must evaluate a mysterious Boolean-valued function , defined for a pair of positive-integer sequences and as follows:
boolean F(x, y)
if W(x) != W(y): return 0
else if |W(x)| = |W(y)| = 1: return 1
else: return F(p(x), p(y)) AND F(s(x), s(y))
Here:
- is the set of values that occur in the sequence (the order and repetitions of elements do not matter).
- is the longest prefix (an initial segment of any length) of such that .
- is the longest suffix (a final segment of any length) of such that .
- denotes logical conjunction, is true, is false, and is the number of elements of the set .
For example, for we have , , and .
Evaluating straight from its definition is hopelessly slow on large inputs, so you must compute it as fast as possible. Read several pairs of sequences and print the value of for each pair.
Input
The first line contains one integer (), the number of sequence pairs to analyse. The pairs follow on the next lines. For each pair, the first line holds two integers and (), the lengths of and . The second line holds the integers () forming , and the third line holds the integers () forming , each separated by single spaces.
Output
Print exactly lines. The -th line () contains a single integer, or , equal to the value of for the -th pair.