Official

D - 魔物の一掃 / Sweeping Out Monsters Editorial by admin Editorial for printing

Claude Opus 5 (High)

Overview

Given \(N\) monsters and \(M\) interval-damage scrolls, this problem asks for the minimum total cost of a subset of scrolls needed to reduce all monsters’ HP to zero or below. Since \(M \leq 15\), we can exhaustively search all subsets of scrolls to use (bit brute-force search).

Analysis

Key Observation 1: The outcome depends solely on the chosen “subset”

Each scroll can be used at most once, and the order of use does not matter. In other words, the answer is determined solely by which subset of scrolls \(S \subseteq \{1,\dots,M\}\) is used.

When subset \(S\) is used, the total damage dealt to monster \(i\) is

\[ D_i(S) = \sum_{j \in S,\ L_j \le i \le R_j} C_j \]

If \(D_i(S) \ge A_i\) holds for all \(i\), the subset is valid, and its cost is \(\sum_{j\in S} W_j\).

Since \(M \leq 15\), there are at most \(2^{15} = 32768\) subsets, so we can check all of them.

Key Observation 2: Represent the “set of scrolls covering monster \(i\)” as a bitmask

For monster \(i\), let the set of scrolls that include \(i\) in their attack range be

\[ \mathrm{cov}_i = \{\, j \mid L_j \le i \le R_j \,\} \]

and represent this as an \(M\)-bit integer (mask). Then,

\[ D_i(S) = \sum_{j \in S \cap \mathrm{cov}_i} C_j \]

which can be computed as the sum of \(C\) for all scrolls contained in \(S \& \mathrm{cov}_i\) (bitwise AND).

Therefore, by precomputing the sum of \(C\) for all masks \(T\), \(\mathrm{sumC}[T]\), and the sum of \(W\), \(\mathrm{sumW}[T]\), the check for a given \(S\) becomes an \(O(N)\) loop (with each monster checked in \(O(1)\)):

\[ \text{for all } i,\ \mathrm{sumC}[S \,\&\, \mathrm{cov}_i] \ge A_i \]

Comparison with a Naive Approach

A naive approach of “for each \(S\), add \(C_j\) to the range \([L_j, R_j]\) for each scroll” takes around \(2^M \cdot (N + M)\) operations. While this might pass in theory (\(32768 \times 215 \approx 7\times10^6\)), the constant factor is heavy and risky in Python. With the bitwise AND approach above, the inner loop consists only of simple array lookups and comparisons, making it fast.

Furthermore, we can apply the following pruning techniques:

  • Monsters with the same \(\mathrm{cov}_i\) can be grouped together: Among monsters with identical \(\mathrm{cov}_i\), we only need to check the one with the maximum HP (if that one is defeated, the others will be too). The number of distinct \(\mathrm{cov}\) values is at most \(\min(N, 2^M)\); in practice, since it is determined by the endpoints of intervals, it is at most \(N\), and often much smaller.
  • Check in descending order of HP: By checking the stricter conditions (which are more likely to fail) first, we can exit the loop earlier upon failure.
  • Skip checking if the cost is already at or above the current best: If sumW[S] >= best, there is no point in verifying the monsters.

Checking for Impossibility

If there is any monster that cannot be defeated even when using all scrolls (\(S = 2^M - 1\)), it cannot be defeated by any subset either, so the answer is \(-1\) (damage is monotonic; that is, if \(S \subseteq S'\), then \(D_i(S) \le D_i(S')\)). Conversely, if using all scrolls defeats every monster, a valid answer is guaranteed to exist.

Algorithm

  1. For each monster \(i\), find the mask \(\mathrm{cov}_i\) of scrolls that cover \(i\) (\(O(NM)\)).
  2. Group the monster conditions by key \(\mathrm{cov}\), retaining only the maximum HP for each key. Sort the resulting list of conditions in descending order of HP.
  3. Precompute \(\mathrm{sumC}[T]\) and \(\mathrm{sumW}[T]\) for all masks \(T\) using DP:
    • Let \(\mathrm{lowbit} = T \,\&\, (-T)\) and its bit index be \(j\).
    • \(\mathrm{sumC}[T] = \mathrm{sumC}[T \oplus \mathrm{lowbit}] + C_j\) (similarly for \(W\)).
  4. Check feasibility for \(S = 2^M-1\). If impossible, output \(-1\).
  5. For all \(S\), if \(\mathrm{sumW}[S] < \mathrm{best}\), verify all conditions; if satisfied, update \(\mathrm{best} \gets \mathrm{sumW}[S]\).
  6. Output \(\mathrm{best}\).

Concrete Example

When \(N=3, A=(5,5,5)\) and the scrolls are: - Scroll 1: \(L=1, R=2, C=5, W=3\) - Scroll 2: \(L=2, R=3, C=5, W=4\)

we have \(\mathrm{cov}_1 = \{1\} = 001_2\), \(\mathrm{cov}_2 = \{1,2\} = 011_2\), \(\mathrm{cov}_3 = \{2\} = 010_2\). For \(S = \{1,2\} = 11_2\), we have \(\mathrm{sumC}[11 \& 001] = 5 \ge 5\), \(\mathrm{sumC}[11 \& 011] = 10 \ge 5\), and \(\mathrm{sumC}[11\&010] = 5 \ge 5\), which succeeds with a cost of \(7\). With \(S=\{1\}\), monster 3 cannot be defeated; with \(S=\{2\}\), monster 1 cannot be defeated; thus, the answer is \(7\).

Complexity

Let \(K\) be the number of conditions after aggregation (\(K \le \min(N, 2^M)\)):

  • Time complexity: \(O(2^M \cdot K + NM)\) (in the worst case \(O(2^M N)\), roughly \(2^{15}\times 200 \approx 6.5\times 10^6\), and significantly smaller in practice due to pruning)
  • Space complexity: \(O(2^M + N)\)

Implementation Points

  • Precomputing \(\mathrm{sumC}\) and \(\mathrm{sumW}\) is essential. Iterating over the set bits of \(S\) each time would result in \(O(2^M M K)\), which is too slow. This can be written concisely using the idiom mask & (-mask) to isolate the lowest set bit and bit_length() - 1 to find its position.

  • The inputs \(L\) and \(R\) are 1-indexed, so when converting them to 0-indexed array slices/ranges, use something like range(L[j]-1, R[j]).

  • HP is up to \(10^9\), and total scroll damage can reach \(15 \times 10^9\), which fits within a 64-bit integer (Python handles arbitrarily large integers automatically, but in C++, make sure to use long long).

  • Aggregating monsters with the same \(\mathrm{cov}\) and sorting them by HP in descending order is an important optimization to enable early termination in the verification loop.

  • The impossibility check (\(-1\)) is done simply by verifying “is it impossible even when using all scrolls?”. Due to the monotonicity of damage, this condition is both necessary and sufficient.

    Source Code

import sys

def main():
    data = sys.stdin.buffer.read().split()
    idx = 0
    N = int(data[idx]); idx += 1
    M = int(data[idx]); idx += 1
    A = [int(data[idx + i]) for i in range(N)]
    idx += N
    L = [0] * M; R = [0] * M; C = [0] * M; W = [0] * M
    for j in range(M):
        L[j] = int(data[idx]); idx += 1
        R[j] = int(data[idx]); idx += 1
        C[j] = int(data[idx]); idx += 1
        W[j] = int(data[idx]); idx += 1

    cov = [0] * N
    for j in range(M):
        bit = 1 << j
        for i in range(L[j] - 1, R[j]):
            cov[i] |= bit

    d = {}
    for i in range(N):
        c = cov[i]
        a = A[i]
        if d.get(c, 0) < a:
            d[c] = a

    items = sorted(d.items(), key=lambda x: -x[1])

    size = 1 << M
    sumC = [0] * size
    sumW = [0] * size
    for mask in range(1, size):
        low = mask & (-mask)
        j = low.bit_length() - 1
        rest = mask ^ low
        sumC[mask] = sumC[rest] + C[j]
        sumW[mask] = sumW[rest] + W[j]

    INF = float('inf')
    best = INF
    # quick feasibility check with full set
    full = size - 1
    ok_full = True
    for c, a in items:
        if sumC[full & c] < a:
            ok_full = False
            break
    if not ok_full:
        sys.stdout.write("-1\n")
        return

    for S in range(size):
        w = sumW[S]
        if w >= best:
            continue
        ok = True
        for c, a in items:
            if sumC[S & c] < a:
                ok = False
                break
        if ok:
            best = w

    sys.stdout.write(str(best) + "\n")

main()

This editorial was generated by claude5opus-high.

posted:
last update: