公式

D - 回転スタンプ / Rotating Stamp 解説 by admin 印刷ページ

Gemini 3.8 Flash (High)

Overview

In this problem, we want to flip at most \(K\) cells on a stamp to maximize the number of cells that receive ink both before and after rotating the stamp \(90\) degrees clockwise.

By connecting the dependencies between cells with directed edges, the problem decomposes into independent cycles of size \(1\) or \(4\). After exhaustively searching each cycle to find the “maximum score for each modification cost”, we can obtain the optimal solution using Group Knapsack DP.

Analysis

1. Condition for a Cell on the Paper to Become “Dark”

Let us use 0-indexing and focus on cell \((r, c)\) on the paper. - First stamping (no rotation): Ink from cell \((r, c)\) of the stamp is transferred. - Second stamping (rotated \(90\) degrees clockwise): According to the problem statement, cell \((i, j)\) of the stamp overlaps with cell \((j, N - 1 - i)\) on the paper. Therefore, letting \((i, j)\) be the cell of the stamp that overlaps with cell \((r, c)\) on the paper, we have: $\(j = r, \quad N - 1 - i = c \implies i = N - 1 - c\)\( This indicates that ink from cell \)(N - 1 - c, r)$ of the stamp is transferred.

Hence, the condition for cell \((r, c)\) on the paper to become dark is that, on the modified stamp, both cell \((r, c)\) and cell \((N - 1 - c, r)\) have ink.

2. Decomposition into Independent Cycles

Whether cell \((r, c)\) becomes dark depends solely on the states of cells \((r, c)\) and \((N - 1 - c, r)\) on the stamp. Thus, let us consider a directed edge from cell \((r, c)\) to cell \((N - 1 - c, r)\).

Following this transition repeatedly will return to the starting cell in at most \(4\) steps (since repeating a \(90\)-degree rotation \(4\) times is a \(360\)-degree rotation, returning to the original position). Specifically, every cell belongs to one of the following cycles: - Cycle of length 1: Only the center cell (\((N-1)/2, (N-1)/2\)) when \(N\) is odd - Cycles of length 4: All other cells

Crucially, the cycles are completely independent of each other. Changing the colors of cells in one cycle has no effect whatsoever on the number of dark cells obtained in other cycles.

3. Local Optimization Within Each Cycle

The cycle length \(L\) is always either \(1\) or \(4\). Therefore, for each cycle, we can examine all possible configurations of modified cells (\(2^L\) states, at most \(2^4 = 16\)).

For each configuration, we compute: - Cost: The number of cells whose color differs from the initial state (\(0 \le \text{cost} \le L\)) - Score: The number of dark cells obtained - For \(L = 1\): \(1\) if the cell has ink, \(0\) otherwise - For \(L = 4\): The number of adjacent pairs of cells in the cycle (\(v_i\) and \(v_{(i+1)\%4}\)) that both have ink

From these, we precompute the maximum score achievable for each cost \(c \in [0, L]\).

4. Integration via Group Knapsack DP

Each cycle can be treated as a “group of items where paying cost \(c\) yields a maximum score \(v\)”. Since at most one cost can be chosen from each cycle, we can find the maximum score achievable with a total cost of at most \(K\) by solving a Group Knapsack DP (equivalent to a multiple-choice knapsack problem).

Algorithm

  1. Cycle Extraction:
    • For the \(N \times N\) grid, start from unvisited cells and follow \((r, c) \to (N - 1 - c, r)\) to decompose the entire grid into independent cycles.
  2. Precomputing the Maximum Value Table for Each Cycle:
    • For each cycle, use bit brute force (checking all \(2^L\) configurations) to compute and record the maximum score best[c] for each cost \(c\) (\(0 \le c \le L\)).
  3. DP (Dynamic Programming):
    • Define \(dp[w]\) as “the maximum number of dark cells obtained using a total cost of \(w\) so far”.
    • Base case: \(dp[0] = 0\), and \(-\infty\) for all other states.
    • Update the transitions sequentially for each cycle: $\(new\_dp[w + c] = \max(new\_dp[w + c], dp[w] + best[c])\)$
  4. Answer Computation:
    • After processing all cycles, the answer is \(\max_{0 \le w \le K} dp[w]\).

Complexity

  • Time Complexity: \(O(N^2 K)\)
    • Cycle decomposition: \(O(N^2)\), as each cell is visited once.
    • Brute force per cycle: There are at most \(N^2/4 + 1\) cycles, and each cycle examines at most \(2^4 = 16\) states, taking \(O(N^2)\) in total.
    • DP updates: There are about \(N^2/4\) cycles, each has \(L+1 \le 5\) transitions, and the maximum cost is \(K\). Thus, the entire DP takes \(O(\frac{N^2}{4} \cdot 5 \cdot K) = O(N^2 K)\).
    • With \(N \le 80\) and \(K \le N^2 \le 6400\), this results in roughly \(N^2 K \approx 4 \times 10^7\) operations, comfortably fitting within the time limit.
  • Space Complexity: \(O(N^2 + K)\)
    • \(O(N^2)\) memory is used to store the stamp grid and cycle structures, and \(O(K)\) memory is used for the DP table.

Implementation Notes

  • Rotation Formula with 0-indexing: In an \(N \times N\) grid, rotating cell \((r, c)\) by \(90\) degrees clockwise moves it to \((c, N - 1 - r)\). Consequently, the stamp cell that lands on paper cell \((r, c)\) after a \(90\)-degree clockwise rotation is \((N - 1 - c, r)\) via the inverse mapping. Using 0-indexing simplifies these formulas nicely.

  • DP Table Size Management: Instead of allocating the DP table up to \(K\) from the very beginning, dynamically expanding its size up to the cumulative length of processed cycles, \(\min(K+1, \sum L + 1)\), eliminates redundant loops in the early iterations and significantly speeds up execution.

    Source Code

import sys


def main():
    input = sys.stdin.read
    data = input().split()
    if not data:
        return

    N = int(data[0])
    K = int(data[1])

    A = []
    idx = 2
    for i in range(N):
        A.append([int(x) for x in data[idx : idx + N]])
        idx += N

    visited = [[False] * N for _ in range(N)]
    cycles = []

    for r in range(N):
        for c in range(N):
            if not visited[r][c]:
                cur_r, cur_c = r, c
                cycle = []
                while not visited[cur_r][cur_c]:
                    visited[cur_r][cur_c] = True
                    cycle.append((cur_r, cur_c))
                    cur_r, cur_c = N - 1 - cur_c, cur_r
                cycles.append(cycle)

    K = min(K, N * N)
    dp = [0]

    for cycle in cycles:
        L = len(cycle)
        orig_vals = [A[r][c] for r, c in cycle]
        best = [-1] * (L + 1)

        for mask in range(1 << L):
            cost = 0
            score = 0
            vals = [(mask >> i) & 1 for i in range(L)]
            for i in range(L):
                if vals[i] != orig_vals[i]:
                    cost += 1
            if L == 1:
                score = vals[0]
            else:
                for i in range(L):
                    if vals[i] == 1 and vals[(i + 1) % L] == 1:
                        score += 1
            if score > best[cost]:
                best[cost] = score

        cur_len = len(dp)
        new_len = min(K + 1, cur_len + L)
        new_dp = [-1] * new_len

        for w, val in enumerate(dp):
            if val < 0:
                continue
            for c in range(L + 1):
                nw = w + c
                if nw < new_len:
                    ns = val + best[c]
                    if ns > new_dp[nw]:
                        new_dp[nw] = ns
        dp = new_dp

    print(max(dp))


if __name__ == "__main__":
    main()

This editorial was generated by gemini-3.8-flash-high.

投稿日時:
最終更新: