Cow Patterns
Time limit1sMemory limit128 MB
Find every length-K window of a spot-count sequence whose relative order matches a given rank pattern.
- Level
Medium7 of 10
- Topics
- String matching, Sliding window, Implementation
- Solved
- No attempts yet
Problem
A group of of Farmer John's cows likes to make trouble. When placed in a line, these troublemakers always stand together in a particular relative order. To find them, FJ has lined up all of his cows, who will file into the barn keeping that order. Help FJ locate every block of consecutive cows in the line that could be the troublemakers.
FJ tells his cows apart by the number of spots on each cow's coat. It is not a perfect method, but it serves his purposes. FJ does not remember the exact number of spots on each troublemaker. He does remember which cows in the group have the same number of spots, and, for any two cows with different counts, which one has more. He writes such a pattern as a sequence of ranks in the range . For example, consider the sequence:
1 4 4 3 2 1
Here FJ is looking for 6 consecutive cows. Cows #1 and #6 have the same number of spots (not necessarily 1) and the fewest among the six (they are labeled '1'). Cow #5 has the second-fewest spots, different from every other cow. Cows #2 and #3 have equal spots, the most among the six.
If the true spot counts of some consecutive cows are:
5 6 2 10 10 7 3 2 9
then only the block 2 10 10 7 3 2 matches the pattern above.
Find every length- block of consecutive cows whose spot counts match the given pattern.
Here a block matches the pattern when the two sequences have exactly the same relative order: for every pair of positions , whether the pattern's -th entry is smaller than, equal to, or greater than its -th entry must hold identically for the block.
Input
- Line 1: Three space-separated integers , , and (, , ).
- Lines 2..N+1: Line contains the number of spots on cow ().
- Lines N+2..N+K+1: Line contains the -th rank of the pattern ().
Output
- Line 1: , the number of starting positions at which the pattern matches.
- Next lines: the starting positions () where the pattern matches, one per line, in increasing order.
If there is no match, print a single line containing 0.
Hint
In the worked example above, comparing the true spot counts 5 6 2 10 10 7 3 2 9 with the pattern 1 4 4 3 2 1 gives exactly one match: the block 2 10 10 7 3 2 starting at position 3.