Meet and Greet

Interview

Time limit1sMemory limit128 MB

Summary
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 00) at time 00, 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 00 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 BB and EE (1≤B≤500001 \le B \le 50000, 1≤E≤500001 \le E \le 50000).
  • The next BB lines: These describe Bessie's movements. Each line contains a positive integer followed by either L or R, where L means left and R means 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 EE 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 33, right by 55, left by 11, and right by 22, and then stands still, while Elsie moves right by 44, left by 11, left by 33, right by 44, and left by 22, and then stands still. Then the two cows meet again after being apart at time 77, time 99, and time 1313, for a total of 33 "moos".

Examples3

  1. Example 1

    Input
    4 5
    3 L
    5 R
    1 L
    2 R
    4 R
    1 L
    3 L
    4 R
    2 L
    
    Expected output
    3
    
  2. Example 2

    Input
    1 1
    1 R
    1 L
    
    Expected output
    0
    
  3. Example 3

    Input
    2 2
    2 R
    2 L
    1 L
    1 R
    
    Expected output
    1