Grass
Time limit1sMemory limit128 MB
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 byXmillimeters. If a plant would become taller thanH, its height becomes exactlyH.L X: the leftmostXplants are completely mowed, so their heights become0.D X: the rightmostXplants are completely mowed, so their heights become0.S X: the lawnmower is set to heightXand used on the whole garden. Every plant taller thanXis cut down toX; 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.