F - Inserting Process 解説 by en_translator
Considering the operations in reverse order, we will count the number of ways to erase one character by one from \(T\) to obtain an empty string.
Consider maintaining the set representation of the positions of the remaining string as \(S=\lbrace S_1,S_2,\ldots,S_k\rbrace\ (1\leq S_1\lt S_2\lt \ldots\lt S_k\leq N)\). Removing a character from the string corresponds to choosing an \(i\) and removing \(S_i\) from \(S\).
However, different ways of removal may result in the same string. For example, if \(T\) is abcade
and \(S=\lbrace 1, 4, 6\rbrace\), removing \(1\) and removing \(4\) both yields ae
. To remove this duplicate, we add the following additional constraint:
- If \(i\geq 2\) and \(T_{S_{i-1}}=T_{S_{i}}\), you are disallowed to remove \(S_i\) (to the right) from \(S\). (In other words, among the interval with repeated letters, always remove the leftmost one first.)
Under this constraint, the problem can be solved with a bit DP (Dynamic Programming). The complexity is \(O(N2^N)\).
mod = 998244353
n = int(input())
t = input()
dp = [0] * (1 << n)
dp[(1 << n) - 1] = 1
for bit in range((1 << n) - 1, -1, -1):
dp[bit] %= mod
pre = "?"
for i in range(n):
if (bit >> i) & 1:
if pre != t[i]:
dp[bit ^ (1 << i)] += dp[bit]
pre = t[i]
print(dp[0])
投稿日時:
最終更新: