A - 階段の水流 / Waterflow on Stairs Editorial by admin Editorial for printing
GPT 5.2 HighOverview
We simulate each operation by “evaporating \(B_i\) from the specified flower pot and flowing the remainder down to the next pot,” then determine the final water amount in each pot.
Analysis
The key insight about this phenomenon is that water moves at most one level per sunlight operation.
In other words, when sunlight hits pot \(i\):
- The water in pot \(i\) always becomes \(0\) (evaporation + all remainder flows out)
- Only the post-evaporation remainder \(\max(0, A_i - B_i)\) flows down
- That remainder is only added to pot \(i+1\) (if \(i=N\), it disappears into the drain)
Further evaporation at the destination (pot \(i+1\)) only occurs when that pot is selected as an operation target in the future.
A naive implementation that “re-examines the state of all pots for each operation” would be \(O(NQ)\), which is too slow for the constraints \(N,Q \le 2\times 10^5\).
However, in reality, each operation only affects pot \(i\) and (if it exists) pot \(i+1\), so we can update in \(O(1)\) per operation.
Algorithm
Maintain the current water amount array as w[0..N-1], and for each operation do the following (converting 1-index to 0-index):
- Let the operation target be \(i\) (0-index)
- Extract the current water
cur = w[i] - The amount flowing after evaporation is
out = max(0, cur - B[i]) - Set
w[i] = 0(because all remainder flows out) - If \(i+1 < N\), then
w[i+1] += out(if it’s the bottom pot, discard it)
For example, with \(N=3\), water \((10,0,0)\), \(B=(3,5,0)\), when sunlight hits pot 1: \(3\) evaporates, and the remaining \(7\) moves to pot 2, resulting in \((0,7,0)\).
Repeating this \(Q\) times gives us the final state.
Complexity
- Time complexity: \(O(N+Q)\) (initial reading + \(O(1)\) per operation)
- Space complexity: \(O(N)\) (water amount array)
Implementation Notes
Don’t overlook that
w[i]=0always holds after an operation (because “all remainder flows down”).When \(i=N\) (the bottom pot), water goes to the drain, so don’t add to
i+1.\(A_i, B_i\) can be up to \(10^9\), and values can grow through addition, so use a sufficiently large integer type (Python’s
int).Source Code
import sys
def read_all_ints():
data = sys.stdin.buffer.read()
res = []
num = 0
in_num = False
for b in data:
if 48 <= b <= 57:
num = num * 10 + (b - 48)
in_num = True
else:
if in_num:
res.append(num)
num = 0
in_num = False
if in_num:
res.append(num)
return res
def main():
v = read_all_ints()
p = 0
N = v[p]
Q = v[p + 1]
p += 2
water = v[p:p + N]
p += N
B = v[p:p + N]
p += N
w = water
b = B
n = N
for _ in range(Q):
i = v[p] - 1
p += 1
cur = w[i]
bi = b[i]
if cur > bi:
out = cur - bi
if i + 1 < n:
w[i + 1] += out
w[i] = 0
sys.stdout.write(" ".join(map(str, w)))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
posted:
last update: