公式

D - 同じ番号で接するカード / Cards Touching with the Same Number 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

We process the cards from left to right and count the number of valid configurations using dynamic programming, where the state consists of the “number of adjacent pairs satisfying the condition” and the “orientation of the last card.”

Furthermore, we reduce the computational complexity by counting whichever target is smaller between the number of equal adjacent pairs and the number of unequal adjacent pairs.

Analysis

Brute Force Is Too Slow

Since there are \(2\) choices (face-up or face-down) for each card, there are \(2^N\) total ways to orient the cards. An approach that enumerates all of them will not pass within the time limit for \(N \leq 2000\).

When Adding the Next Card, Only the Previous Card Is Needed

Consider deciding the orientation of the cards from left to right.

When adding a new card, the only new condition to evaluate is the “boundary with the immediately preceding card.” Therefore, we do not need to remember all previous orientations; it suffices to maintain only the following information:

  • The number of target pairs counted so far
  • Whether the previous card is face-up or face-down

For example, if the previous card is face-up, placing the new card face-up means comparing \(A_{i-1}\) and \(A_i\).

We Can Count Unequal Adjacent Pairs Instead

There are \(N-1\) adjacent boundaries in total, so:

“exactly \(K\) equal adjacent pairs”

can be rephrased as:

“exactly \(N-1-K\) unequal adjacent pairs.”

Thus, by setting \(L=\min(K,N-1-K)\), we can switch what we count as follows:

  • If \(K \leq N-1-K\), count equal adjacent pairs
  • Otherwise, count unequal adjacent pairs

For example, if \(N=5,\ K=3\), instead of counting \(3\) equal pairs, we can count \(1\) unequal pair.

In the code, count_equal indicates whether we are counting equal pairs, and the variable k is replaced with \(L\).

Algorithm

1. DP State

After processing the first \(i\) cards, we maintain the following arrays:

  • dp_a[j]: the number of ways such that there are exactly \(j\) target adjacent pairs and the \(i\)-th card is face-up
  • dp_b[j]: the number of ways such that there are exactly \(j\) target adjacent pairs and the \(i\)-th card is face-down

We maintain \(j\) from \(0\) to \(L\). Since the count will never decrease later, states exceeding \(L\) are not needed.

2. Initialization

With only the first card, there are no adjacent boundaries yet.

Since there is \(1\) way to place it face-up and \(1\) way to place it face-down, we set:

  • dp_a[0] = 1
  • dp_b[0] = 1

and set all other entries to \(0\).

Even if \(A_1=B_1\), choosing face-up and choosing face-down are treated as distinct choices, so we set \(1\) for both.

3. Transitions to the Next Card

Let the values of the previous card be prev_a and prev_b, and the values of the new card be a and b.

For each combination of orientations, determine whether the new boundary counts towards the target as \(0\) or \(1\).

Variable Previous Orientation New Orientation Values to Compare
aa Face-up Face-up prev_a, a
ba Face-down Face-up prev_b, a
ab Face-up Face-down prev_a, b
bb Face-down Face-down prev_b, b

If we are counting equal pairs, the value is \(1\) when the values are equal; if we are counting unequal pairs, the value is \(1\) when the values are unequal.

For instance, if aa = 1, to have a total of \(j\) pairs with the new card face-up, the previous face-up state must have had \(j-1\) pairs.

Therefore, the transitions are as follows:

  • \(\mathrm{next\_a}[j]=\mathrm{dp\_a}[j-aa]+\mathrm{dp\_b}[j-ba]\)
  • \(\mathrm{next\_b}[j]=\mathrm{dp\_a}[j-ab]+\mathrm{dp\_b}[j-bb]\)

Mathematically, state values corresponding to negative indices are treated as \(0\). All calculations are performed modulo \(998244353\).

Regardless of whether the new card is face-up or face-down, the previous card was either face-up or face-down. Because we add these two mutually exclusive cases, we count all valid choices without duplication.

4. Answer

After processing all cards, since the orientation of the last card can be either face-up or face-down, the answer is:

\((\mathrm{dp\_a}[L]+\mathrm{dp\_b}[L])\bmod 998244353\)

Complexity

Let \(L=\min(K,N-1-K)\).

  • Time Complexity: \(O(N(L+1))\)
  • Space Complexity: \(O(L+1)\) auxiliary space for DP

For each card, we update at most \(L+1\) states in constant time. The DP only maintains the arrays for the previous and current steps.

Note that because the provided code reads the entire input at once, the total space complexity including the input storage is \(O(N+L)=O(N)\).

Implementation Details

Do Not Merge States Even If Face-up and Face-down Values Are Equal

Even if \(A_i=B_i\) for a card, choosing face-up and choosing face-down are considered distinct choices. By maintaining and updating dp_a and dp_b separately, they are properly distinguished.

Sentinel Value for Handling Negative Indices

In the provided code, the length of the DP array is set to \(L+2\).

When j - aa (or similar) becomes negative, its value is always \(-1\). Since an index of -1 in Python refers to the last element of the array, keeping the last element always equal to \(0\) allows impossible states to be treated as \(0\) automatically.

Since the updated indices range from \(0\) to \(L\), the last element at index \(L+1\) always remains \(0\). This trick leverages Python’s negative index behavior.

Modulo Operation Needs at Most One Subtraction

Each DP value is always at least \(0\) and less than \(998244353\). Since each transition only adds two values, if the sum is greater than or equal to the modulus, subtracting the modulus once yields the correct remainder.

Source Code

import sys


def main():
    it = iter(map(int, sys.stdin.buffer.read().split()))
    n = next(it)
    k = next(it)

    count_equal = True
    if k > n - 1 - k:
        k = n - 1 - k
        count_equal = False

    mod = 998244353
    size = k + 2

    prev_a = next(it)
    prev_b = next(it)

    dp_a = [0] * size
    dp_b = [0] * size
    dp_a[0] = dp_b[0] = 1

    for i in range(1, n):
        a = next(it)
        b = next(it)

        aa = int((prev_a == a) == count_equal)
        ba = int((prev_b == a) == count_equal)
        ab = int((prev_a == b) == count_equal)
        bb = int((prev_b == b) == count_equal)

        next_a = [0] * size
        next_b = [0] * size

        for j in range(min(i, k) + 1):
            x = dp_a[j - aa] + dp_b[j - ba]
            if x >= mod:
                x -= mod
            next_a[j] = x

            x = dp_a[j - ab] + dp_b[j - bb]
            if x >= mod:
                x -= mod
            next_b[j] = x

        dp_a, dp_b = next_a, next_b
        prev_a, prev_b = a, b

    print((dp_a[k] + dp_b[k]) % mod)


if __name__ == "__main__":
    main()

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

投稿日時:
最終更新: