Radio Contact
InterviewTime limit2sMemory limit512 MB
John and Bessie each walk or wait along their fixed routes to minimize the summed squared distance until both reach their final points.
- Level
Medium5 of 10
- Topics
- Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John lost his favorite cow bell, and Bessie the cow agreed to help him find it. The two spread out and search the farm along different paths, and they keep in touch by radio. The radio batteries are almost empty, so they want to stay close to each other and save power.
Farmer John starts at and follows a path of steps. Each step is one of 'N' (north), 'E' (east), 'S' (south), or 'W' (west). Bessie starts at and follows a path of steps in the same format. The two paths may pass through the same point.
At each time step Farmer John either stays where he is, or takes the next step of his path if any step is left. Bessie makes the same choice for herself. Except for the first time step, where both stand at their starting positions, the radios spend energy equal to the square of the distance between the two positions at every time step.
Plan the movements so that the total energy spent up to the time step where both first stand on the last point of their own path is as small as possible. Report that total.
Input
The first line contains and (). The second line contains and , and the third line contains and (). The fourth line contains a string of length describing Farmer John's path, and the fifth line contains a string of length describing Bessie's path.
Both coordinates stay in the range during the whole journey. East is the direction of increasing , and north is the direction of increasing .
Output
Print one integer, the smallest total energy the radios can spend.