D - 魔物の一掃 / Sweeping Out Monsters 解説 by admin
gpt-6-astra-mediumOverview
We iterate over all subsets of scrolls to use and find the one with the minimum magic power consumption that defeats all monsters. By combining a Gray code and a difference array (imos method), we can inspect each subset efficiently.
Analysis
Exhaustive Search over Scroll Combinations
Each scroll is either used or not used, so there are \(2^M\) possible choices.
Since \(M \leq 15\), we have \(2^M \leq 32768\), which allows us to examine all combinations. Furthermore, because damage is simply additive, the order in which the scrolls are used does not matter.
However, if we add the effect of each chosen scroll to each target monster one by one for every combination, the time complexity would be \(O(2^M MN)\). Since this could take up to about \(10^8\) operations, the execution time might become tight in Python.
Therefore, we use the difference between adjacent combinations to lighten the damage update process.
Changing Only One Scroll at a Time with a Gray Code
If we enumerate subsets in the standard binary order, transitioning from 011 to 100, for example, changes the usage state of three scrolls.
On the other hand, in a Gray code, exactly one bit changes between adjacent values. For example, for \(M=3\), they can be enumerated in the following order:
000 → 001 → 011 → 010 → 110 → 111 → 101 → 100
Regarding a scroll as used when its corresponding bit is \(1\), we can transition to the next combination each time simply by adding or removing a single scroll.
Accelerating Addition and Removal of a Scroll with a Difference Array
The effect of a single scroll is uniform damage over a contiguous interval. Such range additions can be maintained using a difference array.
To add damage \(c\) to the 0-indexed half-open interval \([l,r)\), we only need to update two positions:
diff[l] += c
diff[r] -= c
Taking the prefix sums of diff yields the damage received by each monster. When removing a scroll, we simply add \(-c\) instead of \(c\).
This allows transitioning between combinations in \(O(1)\) time, and checking whether all monsters can be defeated in \(O(N)\) time.
Impossible If Monsters Cannot Be Defeated Even When Using All Scrolls
Since the damage of every scroll is positive, each monster receives the maximum possible damage when all scrolls are used.
Therefore, if there is any monster that cannot be defeated even after using all scrolls, the answer is \(-1\). Conversely, if all monsters can be defeated using all scrolls, the total magic power consumption \(\sum_j W_j\) can serve as an initial value for the answer.
Algorithm
Check the case where all scrolls are used.
- Add the effects of all scrolls to a difference array
total_diff. - Compute the total damage dealt to each monster from the prefix sums.
- If any monster receives less damage than its HP, output \(-1\) and terminate.
- Otherwise, initialize
answerwith the sum of magic power consumption of all scrolls.
- Add the effects of all scrolls to a difference array
Start the search from the empty set.
- Initialize
gray(representing the current subset),cost(magic power consumption), anddiff(difference array) all to \(0\).
- Initialize
Enumerate the remaining subsets in Gray code order.
- Process in the order of \(k=1,2,\ldots,2^M-1\).
- Determine the bit to flip and the corresponding scroll with the following formulas:
bit = k & -k j = bit.bit_length() - 1 gray ^= bitk & -kisolates the lowest set bit (\(1\)) of \(k\). In a Gray code, flipping this bit transitions to the next subset.- If the bit after flipping is \(1\), add scroll \(j\); if it is \(0\), remove it.
- Update
costand the two positions indiffaccording to whether the scroll was added or removed.
Check whether all monsters can be defeated only when the answer can be improved.
- If
cost >= answer, skip the check because it cannot decrease the answer. - Otherwise, take the prefix sums of
diffto determine the damage dealt to each monster. - Terminate the check as soon as a monster receiving less damage than its HP is found.
- If all monsters can be defeated, set
answer = cost.
- If
Finally, output
answer.
The Gray code enumerates every subset exactly once. We only prune combinations whose magic power consumption is greater than or equal to the current answer, so we will never miss a better solution. Therefore, the final answer is the minimum magic power consumption.
Complexity
- Time complexity: \(O(M + N2^M)\)
- Space complexity: \(O(N+M)\)
Updating for each subset takes \(O(1)\), and checking whether all monsters can be defeated takes \(O(N)\) in the worst case. There is no need to store an array for each subset.
Implementation Notes
Convert intervals to 0-indexed half-open intervals.
The input interval \([L_j,R_j]\) corresponds to \([L_j-1,R_j)\) in 0-indexed notation. In the code, only the left endpoint is decremented by \(1\).Set the size of the difference array to \(N+1\).
Even for a scroll with a right endpoint of \(N\), we need to record the end of the interval atdiff[N].State updates are necessary even when skipping the check.
Even ifcost >= answer, we still updategray,cost, anddiff. This is because the subsequent subsets are constructed from the updated state.No need to check the empty set.
Since \(N \geq 1\) and \(A_i \geq 1\) for all \(i\), it is impossible to defeat all monsters without using any scrolls.Using Python’s
for ... elseconstruct.
Theelseblock executes only if the check loop finishes without anybreak. This corresponds to successfully defeating all monsters.Be mindful of integer size.
The total damage and magic power consumption can reach up to \(15 \times 10^9\), which does not fit in a 32-bit signed integer. While this is not an issue in Python, 64-bit integers should be used in other languages.Source Code
import sys
def main():
input = sys.stdin.buffer.readline
N, M = map(int, input().split())
A = list(map(int, input().split()))
L = [0] * M
R = [0] * M
C = [0] * M
W = [0] * M
total_diff = [0] * (N + 1)
for j in range(M):
l, r, c, w = map(int, input().split())
l -= 1
L[j], R[j], C[j], W[j] = l, r, c, w
total_diff[l] += c
total_diff[r] -= c
damage = 0
for i in range(N):
damage += total_diff[i]
if damage < A[i]:
print(-1)
return
answer = sum(W)
diff = [0] * (N + 1)
gray = 0
cost = 0
for k in range(1, 1 << M):
bit = k & -k
j = bit.bit_length() - 1
gray ^= bit
if gray & bit:
delta = C[j]
cost += W[j]
else:
delta = -C[j]
cost -= W[j]
diff[L[j]] += delta
diff[R[j]] -= delta
if cost >= answer:
continue
damage = 0
for i in range(N):
damage += diff[i]
if damage < A[i]:
break
else:
answer = cost
print(answer)
if __name__ == "__main__":
main()
This editorial was generated by gpt-6-astra-medium.