Grass

Time limit1sMemory limit128 MB

Summary
Simulate N up to 1e9 plants under growth, cap, mow-left, mow-right, and clamp operations using an implicit interval structure, answering running sum queries efficiently.
Level

Hard8 of 10

Topics
Segment tree, Intervals, Simulation, Implementation
Solved
No attempts yet

Problem

Edo takes care of the grass in his garden. The garden is represented as a one-dimensional row of exactly N grass plants, ordered from left to right. Initially every plant has height 0 millimeters. No plant can grow higher than H millimeters.

Process M operations in order and output the sum of all plant heights whenever it is requested.

Each operation is one of the following five types.

  • N X: every plant grows by X millimeters. If a plant would become taller than H, its height becomes exactly H.
  • L X: the leftmost X plants are completely mowed, so their heights become 0.
  • D X: the rightmost X plants are completely mowed, so their heights become 0.
  • S X: the lawnmower is set to height X and used on the whole garden. Every plant taller than X is cut down to X; all other plants keep their height.
  • Z: output the current sum of all plant heights.

Input

The first line contains three positive integers N, H, and M: the number of grass plants, the maximum height of a plant, and the number of operations.

1 <= N <= 10^9, 1 <= H <= 10^6, and 1 <= M <= 10^6.

Each of the next M lines describes one operation. The operation is one of the five types described above. Operations N, L, D, and S consist of one uppercase letter and an integer X, separated by one space. Operation Z has no integer after it.

For operations L and D, 1 <= X <= N. For operations N and S, 1 <= X <= H.

Output

For every Z operation, output one line containing one integer: the current sum of all grass heights. The answers must be printed in the same order as the corresponding Z operations in the input.

The sum of heights can be larger than 2^32.

Examples3

  1. Example 1

    Input
    10 1000 5
    Z
    N 10
    Z
    L 3
    Z
    
    Expected output
    0
    100
    70
    
  2. Example 2

    Input
    10 1000 10
    N 10
    L 5
    Z
    N 10
    L 3
    Z
    D 2
    Z
    S 1
    Z
    
    Expected output
    50
    120
    80
    5
    
  3. Example 3

    Input
    7 10 10
    N 9
    Z
    N 9
    Z
    N 5
    Z
    S 1
    Z
    N 10
    Z
    
    Expected output
    63
    70
    70
    7
    70