Painting the Fence
InterviewTime limit1sMemory limit128 MB
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 and performs a sequence of moves (). 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 units away from the origin.
Input
- Line 1: the integer .
- Lines 2 to : each line describes one move as a distance followed by a direction (
LorR), separated by a space, for example15 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 and moves right, left, right, left, and finally right (as two moves of and ). The regions painted at least twice are , , and , for a total length of .