Official

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

gpt-6-astra-medium

Overview

We partition the cells that map to each other under 90-degree rotations into groups and consider how many modifications to allocate to each group. By classifying the groups according to their initial states, we can exploit the properties of how the score increases with modifications to perform knapsack DP efficiently.

Analysis

1. No need to remove ink

Removing ink from a cell will never increase the number of dark cells.

Since the number of modifications is “at most \(K\),” we never need to perform modifications that remove ink. From here on, we only consider modifications that change a \(0\) cell to \(1\).

Also, if we can change all \(0\)s to \(1\)s, the answer is \(N^2\). In the code, this case is handled first.

2. Only cells that map to each other under rotation are related

Let \(R\) be the operation of rotating 90 degrees clockwise.

The condition for cell \(p\) on the paper to become dark is that in the modified stamp, both cell \(p\) and cell \(R^{-1}(p)\) have ink.

Here, repeatedly rotating a cell yields a group of 4 cells:

\(p \rightarrow q \rightarrow r \rightarrow s \rightarrow p\)

However, when \(N\) is odd, the center cell remains in the same position under rotation.

Let \(x,y,z,w\) be the presence of ink (0 or 1) in the 4 cells in rotational order; the number of dark cells obtained from this group is

\(xy+yz+zw+wx\)

In other words, it suffices to count the number of adjacent pairs that are both \(1\) among the 4 cells arranged in a circle.

Different groups do not affect each other.

3. The initial states of groups can be classified into a few types

First, let base be the total number of dark cells before any modifications. In the DP, we only handle the increase from this baseline.

Groups of 4 cells can be classified as follows based on the number and arrangement of \(1\)s. The sequences in the table are in rotational order, and \(g(t)\) is “the maximum score increase when changing \(t\) zeros to ones in that group.”

Type Example of initial state Score before modifications \(g(0),g(1),\ldots\)
All \(0\) 0000 0 \((0,0,1,2,4)\)
One \(1\) 1000 0 \((0,1,2,4)\)
Two adjacent \(1\)s 1100 1 \((0,1,3)\)
Two opposite \(1\)s 1010 0 \((0,2,4)\)
Three \(1\)s 1110 2 \((0,2)\)
Center cell is \(0\) 0 0 \((0,1)\)

For example, for 1100, adding 1 cell increases the score from \(1\) to \(2\), and adding 2 cells increases it to \(4\). Therefore, the increases are \((0,1,3)\).

For groups with all \(1\)s and the center cell that starts as \(1\), we only need to add their scores to base.

4. Modifications can be concentrated within the same type

While the problem can be solved by knapsack DP processing each group individually, the time complexity would be \(O(N^2K)\), which incurs a heavy overhead from the large number of transitions in Python.

Therefore, we focus on the score increases in the table. For every type, the score gain from one additional modification,

\(g(t)-g(t-1)\)

never decreases as \(t\) increases.

For example, in 1000, the score gains for each additional modification are \(1,1,2\).

From this property, we can deduce that for groups of the same type:

At most one group needs to be partially modified.

Indeed, suppose we allocate \(a\) and \(b\) modifications to two groups of the same type, respectively. Assume both are partially modified, with \(1\le a\le b<F\), where \(F\) is the number of modifications required to make all cells in that type \(1\).

If we change the number of modifications from \((a,b)\) to \((a-1,b+1)\), the change in score is

\(\bigl(g(b+1)-g(b)\bigr)-\bigl(g(a)-g(a-1)\bigr)\ge 0\)

In other words, shifting one modification from the group with fewer modifications to the one with more modifications never results in a loss. By repeating this, one group will eventually become unmodified, or the other will become fully modified to all \(1\)s.

Therefore, for groups of the same type, it is sufficient to consider only the following:

  • Unmodified groups
  • Groups fully modified to all \(1\)s
  • At most one partially modified group

Algorithm

1. Enumerate groups formed by rotations

Starting from unvisited cells, find the cells that map to each other under rotations.

For each group:

  • Add the score before modifications to base.
  • Classify it according to the table above and increment the count of that type in counts.

2. Perform DP with the number of modifications as the budget

Define dp[b] as:

The maximum score increase achievable using at most \(b\) modifications in total for the processed types.

Initialize all values to \(0\).

Suppose there are \(c\) groups of a certain type, where the number of modifications to make all cells \(1\) is \(F\), and the score increase at that time is \(G=g(F)\).

We handle these \(c\) groups as follows:

  • \(c-1\) groups: A binary choice between remaining unmodified or being fully modified to all \(1\)s.
  • The remaining 1 group: Freely modified anywhere from \(0\) to \(F\) times.

Since the last group can also be left unmodified or fully modified, this also covers cases where no group is partially modified.

3. Binary decomposition of fully modified groups

The \(c-1\) groups are all identical items with “cost \(F\), score increase \(G\).”

Instead of processing them one by one, we split the count into powers of two \(1,2,4,\ldots\) and the remainder. For example, 13 items can be decomposed into bundles of sizes \(1,2,4,6\).

A bundle of size \(t\) is treated as a single item with:

  • Cost: \(tF\)
  • Score increase: \(tG\)

and we perform a 0/1 knapsack transition.

This allows us to process the \(c-1\) groups in \(O(K\log(c+1))\) time.

4. Process the remaining 1 group

Save the array before updating as old, and try each modification count \(t=0,1,\ldots,F\).

For budgets \(b\ge t\), update:

\(\mathrm{dp}[b]=\max\bigl(\mathrm{dp}[b],\mathrm{old}[b-t]+g(t)\bigr)\)

Since the size of each group is at most 4, this step takes \(O(K)\) time per type.

After processing all types, the final answer is

\(\mathrm{base}+\mathrm{dp}[K]\)

Complexity

The number of types is a constant 6. Since the number of groups of each type is \(O(N^2)\), the total number of bundles after binary decomposition is \(O(\log(N^2+1))\).

  • Time complexity: \(O\bigl(N^2+K\log(N^2+1)\bigr)\)
  • Space complexity: \(O(N^2+K)\)

Implementation Notes

  • Be careful with rotation indexing
    In 0-indexed coordinates, the cell \((i,j)\) rotates to \((j,N-1-i)\). In the code, 1D indices are used, and the rotated position is calculated as j * n + n - 1 - i.

  • Handle the center cell separately
    If a cell rotates to itself, it is the center cell of an odd-sized grid. If this cell has ink, it will be transferred onto itself in both stamping operations, yielding a score of 1.

  • Distinguish arrangements when there are two \(1\)s
    If they are adjacent, the score before modifications is 1; if they are opposite, it is 0. In the code, they are classified based on whether score is 0.

  • Update the 0/1 knapsack in descending order of budget
    To avoid using the same binary-decomposed bundle multiple times within the same transition, iterate through the budget in descending order.

  • Transition from the pre-update DP for the freely modified group
    Always reference old to prevent selecting the same group multiple times.

  • The DP represents an “at most” budget rather than “exact”
    Since choosing not to modify anything is always an option for any budget, dp can be initialized entirely with \(0\).

    Source Code

import sys


def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    n, k = data[0], data[1]
    a = data[2:]
    size = n * n

    if k >= size - sum(a):
        print(size)
        return

    counts = [0] * 6
    seen = bytearray(size)
    base = 0

    for p in range(size):
        if seen[p]:
            continue

        i, j = divmod(p, n)
        q = j * n + n - 1 - i

        if p == q:
            seen[p] = 1
            if a[p]:
                base += 1
            else:
                counts[5] += 1
            continue

        r = size - 1 - p
        s = size - 1 - q
        seen[p] = seen[q] = seen[r] = seen[s] = 1

        x, y, z, w = a[p], a[q], a[r], a[s]
        ones = x + y + z + w
        score = x * y + y * z + z * w + w * x
        base += score

        if ones == 0:
            counts[0] += 1
        elif ones == 1:
            counts[1] += 1
        elif ones == 2:
            counts[2 if score else 3] += 1
        elif ones == 3:
            counts[4] += 1

    if k == 0:
        print(base)
        return

    profiles = (
        (0, 0, 1, 2, 4),
        (0, 1, 2, 4),
        (0, 1, 3),
        (0, 2, 4),
        (0, 2),
        (0, 1),
    )

    dp = [0] * (k + 1)

    for count, gains in zip(counts, profiles):
        if count == 0:
            continue

        full_cost = len(gains) - 1
        full_gain = gains[-1]

        remaining = count - 1
        block = 1
        while remaining:
            take = min(block, remaining)
            cost = take * full_cost
            gain = take * full_gain

            for budget in range(k, cost - 1, -1):
                candidate = dp[budget - cost] + gain
                if candidate > dp[budget]:
                    dp[budget] = candidate

            remaining -= take
            block <<= 1

        old = dp
        dp = old[:]
        for cost in range(1, min(full_cost, k) + 1):
            gain = gains[cost]
            for budget in range(cost, k + 1):
                candidate = old[budget - cost] + gain
                if candidate > dp[budget]:
                    dp[budget] = candidate

    print(base + dp[k])


if __name__ == "__main__":
    main()

This editorial was generated by gpt-6-astra-medium.