Touchbar Typing
InterviewMemory limit1024 MB
Given a word S and a one-row keyboard K, find the minimum finger movement time to type every character of S in order.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Array
- Solved
- No attempts yet
Problem
The Glide Typing task in the Crowdsource app uses a new Google keyboard to type a word by sliding a finger across keys without lifting it. See the animation below.

To make Glide Typing harder, the usual keyboard is replaced by a linear keyboard whose keys are all in one row.
You want to type a word that is characters long. The keyboard has keys. The keys cover every character in , but some keys may share a character. All characters and keys are integers.
You may start with your finger on any key. Moving your finger from a key to an adjacent key takes 1 second. Glide Typing has no pressing. If your finger is on key , which has character , and you want to type the character at index , you glide the finger from key to key , which takes seconds. While your finger is on key , you can type any number of times instantly. You must type one character at a time, so is typed before for each .
For example, let be 1, 2, 2, 3, 4. You can start with your finger on the key with character 1 at index . Then glide to a key with character 2 at index , which takes seconds. Typing character 2 twice takes no extra time, since . Then continue gliding through the remaining characters in order.
Find the minimal time needed to type the word.
Input
The first line contains the number of test cases . test cases follow.
The first line of each test case contains one integer , the length of the word .
The second line contains integers, where each is the character at index .
The third line contains one integer , the length of the keyboard .
The fourth line contains integers, where each is the character of key .
Output
For each test case, output one line in the form Case #$x$: $y$, where is the test case number starting from 1 and is the minimal time needed to type on the keyboard .
Constraints
- .
- Every character in appears at least once in .
- .
- .