Meet and Greet
InterviewTime limit1sMemory limit128 MB
Simulate two cows walking along a line at unit speed and count how many times they meet after being apart, excluding the start.
- Level
Medium4 of 10
- Topics
- Simulation, Implementation, Two pointers, Array
- Solved
- No attempts yet
Problem
As is commonly known, cows are very socially polite creatures: any time two cows meet after being apart, they greet each other with a friendly "moo".
Bessie the cow and her friend Elsie are walking along a long path on the farm. We can think of this path as a one-dimensional number line. Both cows start at the origin (position ) at time , and both walk at the same speed of one unit of distance per unit of time.
Given a description of each cow's movements, determine the number of "moos" exchanged. A "moo" happens every time the two cows arrive at the same position at the same moment after having been apart. Their shared starting position at the origin at time does not count as a "moo". While the two cows walk together side by side at the same position, only the moment they first meet counts as a single "moo".
The two cows may stop moving at different times, and neither cow travels for more than 1,000,000 units of time.
Input
- Line 1: Two space-separated integers and (, ).
- The next lines: These describe Bessie's movements. Each line contains a positive integer followed by either
LorR, whereLmeans left andRmeans right, and the integer is the distance moved in that direction. Since the speed is one unit per unit of time, this movement also takes that many units of time. - The next lines: These describe Elsie's movements, in the same format.
The total time each cow spends walking is at most 1,000,000.
Output
- A single integer: the number of "moos" exchanged by the two cows. Their initial shared position at the origin does not cause a "moo".
Hint
Suppose Bessie moves left by , right by , left by , and right by , and then stands still, while Elsie moves right by , left by , left by , right by , and left by , and then stands still. Then the two cows meet again after being apart at time , time , and time , for a total of "moos".