DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Dynamic Nonogram

Back to problem

Editorial

Let KKK be the current sequence length and let SSS be the sum of its elements. If K=0K=0K=0, the answer is 000.

For K≥1K \ge 1K≥1, the minimum width required by all components and the mandatory single uncolored cells between them is

L=S+K−1.L=S+K-1.L=S+K−1.

A valid coloring exists, so L≤WL \le WL≤W. Define the number of extra uncolored cells as

D=W−L.D=W-L.D=W−L.

Let pip_ipi​ be the starting cell of component iii when every component is packed as far left as possible. When everything is packed as far right as possible, every component starts exactly DDD cells later, so component iii starts at pi+Dp_i+D.

The cells covered by component iii in every valid coloring are exactly the overlap of these two intervals. Its size is

max⁡(0,Ai−D).\max(0,A_i-D).max(0,Ai​−D).

No cell outside these intervals is forced. Let jjj be the number of left-packed components that end before such a cell. Place all DDD extra uncolored cells in the gap between components jjj and j+1j+1j+1. The first jjj components are then left-packed and the remaining components are right-packed. The cases and mean the outer gaps before the first component and after the last component. In this coloring, the cell is uncolored.

Therefore, the answer is

∑i=1Kmax⁡(0,Ai−D)=∑Ai>DAi−D⋅#{i:Ai>D}.\sum_{i=1}^{K}\max(0,A_i-D) = \sum_{A_i>D}A_i-D\cdot \#\{i:A_i>D\}.i=1∑K​max(0,A

The insertion position does not affect this formula. We only need the number of current values, their sum, and their frequency distribution.

Collect every XXX appearing in a type-111 query and coordinate-compress them. Maintain two Fenwick trees over the compressed values:

  • the current frequency of each value;
  • the current sum contributed by each value.

An insertion or deletion updates one position in both trees. An upper_bound and two suffix queries give the count and sum of all values greater than DDD.

Each query takes O(log⁡Q)O(\log Q)O(logQ) time. The total time complexity is O(Qlog⁡Q)O(Q\log Q)O(QlogQ) and the memory complexity is O(Q)O(Q)O(Q).

pi​+
D
j=0j=0
j=0
j=Kj=Kj=K
i
​
−
D)=
Ai​>D∑​Ai​−
D⋅
#{i:
Ai​>
D}.