John and Bessie each walk or wait along their fixed routes to minimize the summed squared distance until both reach their final points.
Medium5Dynamic programmingInterviewNo attempts yetTime limit2sMemory limit512 MBFarmer 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 (fx,fy) and follows a path of N steps. Each step is one of 'N' (north), 'E' (east), 'S' (south), or 'W' (west). Bessie starts at (bx,by) and follows a path of M 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.
The first line contains N and M (1≤N,M≤1000). The second line contains fx and fy, and the third line contains bx and by (0≤fx,fy,bx,by≤1000). The fourth line contains a string of length N describing Farmer John's path, and the fifth line contains a string of length M describing Bessie's path.
Both coordinates stay in the range 0≤x,y≤1000 during the whole journey. East is the direction of increasing x, and north is the direction of increasing y.
Print one integer, the smallest total energy the radios can spend.