Official
F - Sum = 0 Editorial by en_translator
Hint
Consider the following problem. > There is a sequence of non negative integers $A=(A_1,A_2,\ldots,A_N)$ of length $N$. Given an integer $S$, determine if there exists a length-$N$ integer sequence$X=(X_1,X_2,\ldots,X_N)$ that satisfies the following condition; report one if it exists. > - $0\leq X_i\leq A_i$ > - $\sum X = S$ Obviously, $\sum A\geq S$ is necessary for the existence. This is actually sufficient. If exists, it can be constructed by inspecting the elements from the beginning and letting $X_i$ as large as possible greedily. The original problem can be solved almost in the same way.If \(\sum L>0\), then \(\sum X\geq \sum L>0\), so no \(X\) satisfies the conditions. Likewise, if \(\sum R<0\), then no \(X\) satisfies the condition because \(\sum X\leq \sum R <0\).
Otherwise, there always exists a conforming \(X\).
For each \(i=1,2,\ldots,N\), initialize with \(X_i=L_i\), then one can greedily determine the values for \(i=1,2,\ldots,N\) in order. Specifically, one can do as follows.
- For each \(i=1,2,\ldots\), repeat incrementing the value \(X_i\) by \(+1\) while \(X_i<R_i\) and \(\sum X<0\).
However, doing this naively does not finish within the time limit. The value to add to \(X_i\) can be found fast as follows.
- For \(i=1,2,\ldots\), let \(D_i=\min(R_i-L_i,-\sum X)\). Increment the value \(X_i\) by \(+D_i\).
The complexity is \(O(N)\).
N = int(input())
L, R = [0] * N, [0] * N
for i in range(N):
L[i], R[i] = map(int, input().split())
if sum(L) > 0 or sum(R) < 0:
print("No")
exit()
X = L.copy()
sumX = sum(X)
for i in range(N):
d = min(R[i] - L[i], -sumX)
sumX += d
X[i] += d
print("Yes")
print(*X)
posted:
last update: