公式

D - 回転スタンプ / Rotating Stamp 解説 by admin

Claude Opus 5 (High)

Overview

Cells that map to each other under a “clockwise \(90^\circ\) rotation” form cyclic groups of length \(4\) (when \(N\) is odd, only the center cell forms a group of length \(1\)), and the number of dark cells is determined independently for each group. For each group, we can tabulate “how many dark cells are gained for how many inversions,” and then solve the problem using knapsack DP with the number of inversions \(K\) as the capacity.

Analysis

1. Formulating the condition for a cell to be “dark”

On the \(1\)st press (no rotation), ink is applied to the paper cell \((i,j)\) when \(A_{i,j}=1\).

On the \(2\)nd press (clockwise \(90^\circ\) rotation), the stamp cell \((i,j)\) maps to the paper cell \((j,\;N-i+1)\). Therefore, the stamp cell that applies ink to the paper cell \((p,q)\) satisfies: $\(j=p,\quad N-i+1=q \iff (i,j)=(N-q+1,\;p)\)$ Thus:

Paper cell \((p,q)\) is dark \(\iff A_{p,q}=1\) and \(A_{N-q+1,\,p}=1\)

2. Decomposing into rotation “orbits”

Considering the mapping $\(\sigma(p,q)=(N-q+1,\;p)\)\( the condition above can be written as "\)A\( is \)1\( at both \)(p,q)\( and \)\sigma(p,q)\(." Since \)\sigma\( represents a \)90^\circ\( rotation of the grid, applying \)\sigma\( repeatedly always returns to the starting position in \)4$ steps. That is, the set of all cells is partitioned into:

  • Orbits (cycles) of length \(4\): \(c_0 \to c_1=\sigma(c_0) \to c_2 \to c_3 \to c_0\)
  • An orbit of length \(1\) consisting only of the center cell when \(N\) is odd

(Orbits of length \(2\) do not exist, because \(\sigma^2\) is a \(180^\circ\) rotation, whose only fixed point is the center).

Letting the values along the orbit be \(v_0,v_1,v_2,v_3\) (\(v_k = A_{c_k}\)), the number of dark cells generated by this orbit is $\(\#\{\,k \;:\; v_k = v_{k+1} = 1\,\}\quad(\text{indices are } \bmod 4)\)\( which is **the number of adjacent pairs of \)1\(s arranged in a cycle**. The center cell (length \)1\() maps to itself under \)\sigma\(, so it becomes \)1\( dark cell if \)A=1$.

Crucially, the orbits are completely independent. Inverting cells in one orbit does not affect the darkness of cells in any other orbit.

3. Orbit states and achievable values

The value of a cyclic \(4\)-bit state is uniquely determined by the number and arrangement of \(1\)s.

State Number of dark cells
Four \(1\)s (1111) \(4\)
Three \(1\)s (1110) \(2\)
Two \(1\)s, adjacent (1100) \(1\)
Two \(1\)s, diagonal (1010) \(0\)
One \(1\) (1000) \(0\)
Zero \(1\)s (0000) \(0\)

Therefore, for each orbit, we add its “current value” to base, and create a table of the additional gain \(g\) obtained by paying an additional cost \(c\) (number of inversions) (dominated choices are omitted).

Initial state Addition to base Choices \((c, g)\)
Four \(1\)s \(+4\) None
Three \(1\)s \(+2\) \((1,+2)\)
Two \(1\)s, adjacent \(+1\) \((1,+1),\;(2,+3)\)
Two \(1\)s, diagonal \(+0\) \((1,+2),\;(2,+4)\)
One \(1\) \(+0\) \((1,+1),\;(2,+2),\;(3,+4)\)
Zero \(1\)s \(+0\) \((2,+1),\;(3,+2),\;(4,+4)\)
Center cell \(A=1\) \(+1\) None
Center cell \(A=0\) \(+0\) \((1,+1)\)

(Example: For diagonal 1010, changing \(1\) cell to \(1\) yields 1110 with value \(0\to 2\), and changing \(2\) cells yields 1111 with value \(4\). When there are four \(0\)s, inverting only \(1\) cell still yields a value of \(0\), so the choice with cost \(1\) is meaningless.)

4. Why naive approaches fail

  • Searching all subsets of cells to invert takes \(2^{N^2}\) operations, which is impossible.
  • A greedy approach like “prioritizing the largest gain per inversion” fails. Looking at the table above, for example, the additional gains for an orbit with “one \(1\)” are \(+1,+2,+4\); the marginal gain increases as the cost increases (convex), meaning partially inverting can be suboptimal. Counterexample: Suppose we have orbit X (two \(1\)s, adjacent) and orbit Y (one \(1\)), and \(K=2\). The optimal choice is to complete X for a gain of \(+3\). However, if we greedily pick the move with marginal gain \(+1\) in Y first, we end up with a total gain of only \(+2\).

Therefore, we must solve a grouped (multiple-choice) knapsack problem via DP, where we choose exactly one option (including doing nothing) from each orbit.

Algorithm

  1. Traverse all cells using visited, and from each unvisited cell, repeatedly apply \(\sigma\) (in 0-indexed coordinates, \((i,j)\mapsto(N-1-j,\,i)\)) to enumerate orbits.
  2. From the initial state of each orbit, compute base (the number of dark cells without any inversions) and construct the list of choices \((c,g)\).
  3. Run knapsack DP over the lists of choices:
    • dp[c] = maximum additional gain using at most \(c\) inversions.
    • Process orbits one by one, updating ndp[i+c] = max(ndp[i+c], dp[i] + g) across all choices (where “do nothing” corresponds to \((0,0)\)).
    • Taking the prefix maximum after processing each orbit to make dp monotonically non-decreasing maintains the meaning of “at most \(c\)” and simplifies the implementation.
  4. The answer is base + dp[min(K, total_cost_limit)].

For optimizations:

  • If \(K\) exceeds the sum of the cost limits of all orbits, clip it to that sum (avoiding redundant iterations even when \(K\) can be \(N^2\)).
  • Only extend the DP array length up to “the sum of the maximum costs of orbits processed so far” (at most \(+4\) per orbit).

Applying these is sufficiently fast (since there are only \(6\) types of items, grouping identical types into a bounded knapsack problem makes it even faster).

Complexity

The number of orbits is \(M=\lceil N^2/4\rceil \le 1600\), the knapsack capacity is \(\min(K,\,4M)=O(N^2)\), and each orbit has at most \(4\) choices.

  • Time complexity: \(O(N^2 \cdot \min(K, N^2)) = O(N^4)\) (around \(2\times10^7\) updates for \(N=80\))
  • Space complexity: \(O(N^2)\)

Implementation Details

  • In 0-indexed coordinates, the rotation mapping is \((i,j)\to(N-1-j,\,i)\). Be careful not to confuse it with the 1-indexed \((p,q)\to(N-q+1,p)\). (Even if you accidentally rotate in the opposite direction, the set of orbits and the “number of cyclically adjacent pairs of \(1\)s” remain the same, so the answer does not actually change; however, it is best to be precise with derivations).

  • When there are two \(1\)s, deciding between “adjacent” and “diagonal” can be determined by whether v0 == v2 (i.e., whether \(v_0=v_2=1\) or \(v_0=v_2=0\)) when ordered along the orbit \(v_0,v_1,v_2,v_3\).

  • When \(N\) is odd, the center cell forms an orbit of length \(1\), so do not forget to handle this case.

  • If dp represents “cost exactly \(c\),” handling unreachable states is cumbersome. It is safer to take prefix maximums after each step to maintain “maximum for at most \(c\)” (in the end, you only need to read dp[capacity]).

  • Check that edge cases such as \(K=0\) or all cells being \(1\) (empty choice list) are handled naturally.

    Source Code

import sys

def main():
    data = sys.stdin.buffer.read().split()
    N = int(data[0]); K = int(data[1])
    A = [int(x) for x in data[2:2 + N * N]]

    visited = bytearray(N * N)
    base = 0
    items = []
    for i in range(N):
        rowoff = i * N
        for j in range(N):
            if visited[rowoff + j]:
                continue
            cells = []
            a, b = i, j
            while True:
                idx = a * N + b
                if visited[idx]:
                    break
                visited[idx] = 1
                cells.append(idx)
                a, b = N - 1 - b, a
            if len(cells) == 1:
                if A[cells[0]] == 1:
                    base += 1
                else:
                    items.append(((0, 0), (1, 1)))
                continue
            v0 = A[cells[0]]; v1 = A[cells[1]]; v2 = A[cells[2]]; v3 = A[cells[3]]
            ones = v0 + v1 + v2 + v3
            if ones == 4:
                base += 4
            elif ones == 3:
                base += 2
                items.append(((0, 0), (1, 2)))
            elif ones == 2:
                if v0 == v2:
                    # opposite
                    items.append(((0, 0), (1, 2), (2, 4)))
                else:
                    base += 1
                    items.append(((0, 0), (1, 1), (2, 3)))
            elif ones == 1:
                items.append(((0, 0), (1, 1), (2, 2), (3, 4)))
            else:
                items.append(((0, 0), (2, 1), (3, 2), (4, 4)))

    if not items:
        print(base)
        return

    total = 0
    for o in items:
        total += o[-1][0]
    if K > total:
        K = total
    if K <= 0:
        print(base)
        return

    items.sort(key=lambda o: o[-1][0])

    dp = [0]
    cur = 0
    for opts in items:
        mc = opts[-1][0]
        nm = cur + mc
        if nm > K:
            nm = K
        ndp = [0] * (nm + 1)
        L = cur
        for c, g in opts:
            hi = nm - c
            if hi > L:
                hi = L
            if hi < 0:
                continue
            if g == 0:
                # just copy shifted (c==0 case typically)
                for i in range(hi + 1):
                    d = dp[i]
                    if d > ndp[i + c]:
                        ndp[i + c] = d
            else:
                for i in range(hi + 1):
                    v = dp[i] + g
                    if v > ndp[i + c]:
                        ndp[i + c] = v
        m = 0
        for i in range(nm + 1):
            t = ndp[i]
            if t > m:
                m = t
            else:
                ndp[i] = m
        dp = ndp
        cur = nm

    print(base + dp[cur])

main()

This editorial was generated by claude5opus-high.