This page is still under construction.

Parts of this page are still being built. What you see may change.

Painting the Fence

Interview

Time limit1sMemory limit128 MB

Summary
Bessie walks back and forth along a line, each pass adding a coat; find the total length covered by at least two coats.
Level

Medium6 of 10

Topics
Prefix sum, Sorting, Intervals, Simulation
Solved
No attempts yet

Problem

A farmer paints the long fence beside his barn by attaching a paint brush to his cow, Bessie. Think of the fence as a one-dimensional number line. As Bessie walks back and forth, every segment of the fence she passes over receives one coat of paint.

Bessie starts at position 00 and performs a sequence of NN moves (1≤N≤1000001 \le N \le 100000). Each move is given as a distance and a direction: L means she moves that many units to the left, and R means she moves that many units to the right. Every point she crosses during a move receives one additional coat of paint.

Given all of Bessie's moves, determine the total length of the fence that ends up with at least two coats of paint (areas with only a single coat may wash off during heavy rain). Bessie never moves more than 10910^9 units away from the origin.

Input

  • Line 1: the integer NN.
  • Lines 2 to N+1N+1: each line describes one move as a distance followed by a direction (L or R), separated by a space, for example 15 L.

Output

  • A single line containing the total length of the fence covered by at least two coats of paint.

Hint

The number of coats on a point equals the number of times Bessie passes over it.

For example, suppose Bessie starts at 00 and moves 22 right, 66 left, 11 right, 88 left, and finally 33 right (as two moves of 11 and 22). The regions painted at least twice are [−11,−8][-11, -8], [−4,−3][-4, -3], and [0,2][0, 2], for a total length of 66.

Examples2

  1. Example 1

    Input
    6
    2 R
    6 L
    1 R
    8 L
    1 R
    2 R
    
    Expected output
    6
    
  2. Example 2

    Input
    1
    5 R
    
    Expected output
    0