Amusement Park Queue
InterviewTime limit1sMemory limit128 MB
Two people walk a fixed grid path one step per minute, offset by K minutes; count the minutes their cells touch in any of eight directions.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation, Geometry, Array
- Solved
- No attempts yet
Problem
Mirko and Slavko decided to spend their day off at the amusement park. The most popular ride there is the water slide, and the line at its entrance is always full.
The line is a chain of cells on a grid. It starts at cell 1 and ends at cell . The picture below shows the layout of a line with a minute wait, which is together with the path string RRRRDLLLLDD.

Every place ahead of Mirko was taken when he joined the line. After one minute the person at the end of the line gets on the slide, everyone still in the line moves forward one cell, and one new person joins the line.
Slavko ran to the hot dog stand before joining the line, so he got in exactly minutes after Mirko.
The two chat while the cells they stand on touch in one of the eight directions (up, down, left, right, and the four diagonals). For how many minutes do they chat while they wait?
In the layout above, if Slavko joins two minutes after Mirko, they spend three minutes chatting while they wait.
- the minute Mirko is on cell 6 and Slavko is on cell 4
- the minute Mirko is on cell 7 and Slavko is on cell 5
- the minute Mirko is on cell 11 and Slavko is on cell 9
Input
The first line contains the length of the line () and, separated by a space, a string of uppercase letters that describes the layout. The string gives the path every waiting guest walks, starting from cell 1. The letters are 'L', 'R', 'U', 'D', and they mean a move to the cell left of, right of, above, and below the current one.
The second line contains a natural number (), how many minutes after Mirko Slavko joined the line.
The string on the first line always describes a valid layout, so the line never crosses itself.
Output
Print how many minutes Mirko and Slavko are close enough to chat.