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 along a number line and each segment she covers gains a coat of paint; find the total length covered by at least K coats.
Level

Medium6 of 10

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

Problem

Farmer John has devised a brilliant method to paint the long fence next to his barn (think of the fence as a one-dimensional number line). He attaches a paint brush to his favorite cow Bessie, then relaxes with a cold glass of water while Bessie walks back and forth across the fence, painting one coat over every segment she passes.

Bessie starts at position 00 and performs a sequence of NN moves (1≤N≤100,0001 \le N \le 100{,}000). For example, the move "10 L" means Bessie moves 1010 units to the left, and "15 R" means she moves 1515 units to the right. Every segment she walks over receives one coat of paint. During her walk Bessie moves at most 1,000,000,0001{,}000{,}000{,}000 units away from the origin.

Given all of Bessie's moves, find the total length (area) of the fence that is painted with at least KK coats.

Input

  • Line 1: Two space-separated integers NN and KK.
  • Lines 2 to N+1N+1: Each line describes one of Bessie's moves (for example, "15 L"): a distance followed by a direction character, L (left) or R (right).

Output

  • Line 1: The total length of the fence painted with at least KK coats.

Hint

Suppose N=6N = 6, K=2K = 2, and Bessie moves 22 right, 66 left, 11 right, 88 left, 11 right, then 22 right. The area painted with at least 22 coats is 66, consisting of the intervals [-11, -8], [-4, -3], and [0, 2].

Examples2

  1. Example 1

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

    Input
    6 1
    2 R
    6 L
    1 R
    8 L
    1 R
    2 R
    
    Expected output
    13