公式

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

gpt-6-astra-medium

Overview

We divide the cells that map to each other under \(90\)-degree rotations into groups (orbits). For each group, we determine “the maximum number of dark cells that can be produced by modifying a certain number of cells.” We then combine these using knapsack DP to find the maximum score with at most \(K\) modifications.

Analysis

1. Removing ink is unnecessary

Removing ink from a cell will never increase the number of cells on the paper that become dark.

Therefore, among the optimal modification strategies, there is one that only modifies cells without ink from \(0\) to \(1\). Hereafter, we consider only such modifications.

Additionally, if the total number of cells with \(0\) in the initial state is at most \(K\), we can turn all cells into \(1\). In this case, the answer is \(N^2\).

2. Conditions for a cell to become dark

Let \(R\) denote a clockwise \(90\)-degree rotation, and let \(B_p\) denote the presence or absence of ink on cell \(p\) of the stamp after modification.

For cell \(R(p)\) on the paper:

  • In the first stamp, ink is transferred from cell \(R(p)\) of the stamp.
  • In the second stamp, ink is transferred from cell \(p\) of the stamp.

Therefore, the condition for this cell to become dark is \(B_p=B_{R(p)}=1\).

In other words, if two cells adjacent under rotation are both \(1\), one dark cell is formed.

3. Partitioning cells by rotational orbits

Repeatedly rotating a cell results in:

\(p \to R(p) \to R^2(p) \to R^3(p) \to p\)

which returns to the original cell in at most \(4\) steps. We call a set of cells that map to each other under rotation an “orbit.”

A typical orbit consists of \(4\) cells, while the center cell (when \(N\) is odd) forms an orbit of size \(1\).

Cells \(p\) and \(R(p)\), which determine whether a cell becomes dark, always belong to the same orbit. Therefore, different orbits do not affect each other, and their scores can be computed independently and summed up.

Arranging the cells in an orbit in rotational order, and letting their modified states be \(b_0,b_1,\ldots,b_{m-1}\), the score for that orbit is:

\(\displaystyle \sum_{t=0}^{m-1} b_t b_{(t+1)\bmod m}\)

For example, when the state of \(4\) cells is \((1,0,0,0)\):

  • With no modifications, the score is \(0\)
  • Changing an adjacent \(0\) to \(1\) to make it \((1,1,0,0)\), the score is \(1\)
  • Changing all cells to \(1\), the score is \(4\)

Note that the first and last elements are also adjacent under rotation.

4. Using brute force within orbits and DP instead of global brute force

Enumerating the modified states of all cells would yield up to \(2^{N^2}\) possibilities, which will not finish in time.

On the other hand, each orbit has at most \(4\) cells, so it has at most \(2^4=16\) states. For each orbit, we can compute:

\(\mathrm{best}[c] =\) the maximum score of that orbit when modifying exactly \(c\) cells

by brute force.

The remaining task is to decide how many modifications to allocate to each orbit. Since the effect of a modification depends on the surrounding cells’ states, instead of simply picking cells greedily, we find the optimal combination using knapsack DP.

Algorithm

1. Check if all cells can be made \(1\)

Count the number of \(0\)s in the input. If this is at most \(K\), output \(N^2\) and terminate.

2. Enumerate orbits

When an unvisited cell is found, repeatedly rotate it by \(90\) degrees and collect all cells until returning to the starting cell.

Using \(0\)-based indexing in the code, the rotated coordinates are:

\((r,c)\to(c,N-1-r)\)

By marking the collected cells as visited, each orbit is processed exactly once.

3. Compute \(\mathrm{best}\) for each orbit

Represent the initial state within the orbit as a bitmask initial, and enumerate all modified states mask.

Since there is no need to turn cells that are initially \(1\) into \(0\), we only examine states that satisfy:

(mask & initial) == initial

For each state, compute the following:

  • Number of modifications: the number of set bits in mask ^ initial
  • Score: the number of positions where adjacent bits in rotational order are both \(1\)

Letting \(c\) be the number of modifications and \(s\) be the score, update:

\(\mathrm{best}[c]\gets\max(\mathrm{best}[c],s)\)

4. Combine using knapsack DP

Define:

\(\mathrm{dp}[k] =\) the maximum score when modifying exactly \(k\) cells across the processed orbits.

Initialize \(\mathrm{dp}[0]=0\) and set all other values to a sufficiently small value representing unreachable states.

When processing a new orbit, for each modification count \(c\) in that orbit, transition via:

\(\mathrm{ndp}[k+c]\gets\max\bigl(\mathrm{ndp}[k+c],\mathrm{dp}[k]+\mathrm{best}[c]\bigr)\)

considering only values satisfying \(k+c\le K\).

Since all possible modification counts are tested for each orbit, this DP exhaustively considers all valid modification allocations. Furthermore, because orbits do not affect each other, it is guaranteed that the scores can be safely added together.

5. Find the answer

Since the number of modifications is “at most \(K\),” the answer is:

\(\displaystyle \max_{0\le k\le K}\mathrm{dp}[k]\)

after processing all orbits.

Complexity

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

The number of orbits is \(O(N^2)\). For each orbit, state enumeration takes at most \(16\) operations, and the number of additional modification counts tested in the DP is at most \(5\), so processing each orbit takes \(O(K+1)\) time.

For space complexity, \(O(N^2)\) is required for the grid and the visited array, and \(O(K)\) for the DP array.

Implementation Notes

  • The center cell can be handled in the same way.
    When an orbit has size \(1\), the score calculation checks the same bit with itself. If it is \(1\), ink is transferred twice onto the same cell of the paper, so the score correctly becomes \(1\).

  • Use a separate array for DP transitions.
    Transitioning from dp to ndp prevents using the same orbit multiple times.

  • Only iterate over reachable modification counts.
    The variable limit in the code is the minimum of the total modifiable cells in the processed orbits and \(K\). Using this avoids iterating over ranges that cannot be reached yet.

    Source Code

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N, K;
    cin >> N >> K;

    vector<vector<int>> A(N, vector<int>(N));
    int zeros = 0;
    for (auto &row : A) {
        for (int &x : row) {
            cin >> x;
            zeros += (x == 0);
        }
    }

    if (K >= zeros) {
        cout << N * N << '\n';
        return 0;
    }

    vector<vector<bool>> visited(N, vector<bool>(N, false));
    const int NEG = -1000000000;
    vector<int> dp(K + 1, NEG), ndp(K + 1, NEG);
    dp[0] = 0;
    int limit = 0;

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            if (visited[i][j]) continue;

            vector<pair<int, int>> orbit;
            int r = i, c = j;
            do {
                visited[r][c] = true;
                orbit.emplace_back(r, c);
                int nr = c;
                int nc = N - 1 - r;
                r = nr;
                c = nc;
            } while (r != i || c != j);

            int m = static_cast<int>(orbit.size());
            int initial = 0;
            for (int t = 0; t < m; ++t) {
                auto [x, y] = orbit[t];
                if (A[x][y]) initial |= 1 << t;
            }

            int available = m - __builtin_popcount((unsigned)initial);
            array<int, 5> best;
            best.fill(NEG);

            for (int mask = 0; mask < (1 << m); ++mask) {
                if ((mask & initial) != initial) continue;

                int cost = __builtin_popcount((unsigned)(mask ^ initial));
                int score = 0;
                for (int t = 0; t < m; ++t) {
                    if ((mask & (1 << t)) &&
                        (mask & (1 << ((t + 1) % m)))) {
                        ++score;
                    }
                }
                best[cost] = max(best[cost], score);
            }

            int nextLimit = min(K, limit + available);
            fill(ndp.begin(), ndp.begin() + nextLimit + 1, NEG);

            for (int used = 0; used <= limit; ++used) {
                if (dp[used] == NEG) continue;
                int maxAdd = min(available, K - used);
                for (int add = 0; add <= maxAdd; ++add) {
                    ndp[used + add] =
                        max(ndp[used + add], dp[used] + best[add]);
                }
            }

            dp.swap(ndp);
            limit = nextLimit;
        }
    }

    cout << *max_element(dp.begin(), dp.begin() + limit + 1) << '\n';
    return 0;
}

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

投稿日時:
最終更新: