結果
| 問題 |
No.2019 Digits Filling for All Substrings
|
| コンテスト | |
| ユーザー |
gew1fw
|
| 提出日時 | 2025-06-12 19:03:29 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,138 bytes |
| コンパイル時間 | 269 ms |
| コンパイル使用メモリ | 82,160 KB |
| 実行使用メモリ | 102,000 KB |
| 最終ジャッジ日時 | 2025-06-12 19:03:46 |
| 合計ジャッジ時間 | 4,038 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | TLE * 1 -- * 29 |
ソースコード
import sys
from collections import defaultdict
MOD = 998244353
def main():
N = int(sys.stdin.readline())
S = sys.stdin.readline().strip()
# Precompute prefix sum_mod and cnt_q
prefix_sum = [0] * (N + 1)
prefix_cnt_q = [0] * (N + 1)
for i in range(1, N+1):
c = S[i-1]
if c == '?':
prefix_cnt_q[i] = prefix_cnt_q[i-1] + 1
prefix_sum[i] = prefix_sum[i-1]
else:
digit = int(c)
prefix_sum[i] = (prefix_sum[i-1] + digit) % 3
prefix_cnt_q[i] = prefix_cnt_q[i-1]
# Precompute dp[k][s] for 0 <= k <= N, 0 <= s <3
max_k = N
dp = [[0]*3 for _ in range(max_k + 1)]
dp[0][0] = 1
for k in range(max_k):
for s in range(3):
if dp[k][s] == 0:
continue
# Multiply by the transition counts
add0 = dp[k][s] * 4 # contribute 0 mod3
add1 = dp[k][s] * 3 # contribute 1 mod3
add2 = dp[k][s] * 3 # contribute 2 mod3
dp[k+1][(s + 0) % 3] += add0
dp[k+1][(s + 1) % 3] += add1
dp[k+1][(s + 2) % 3] += add2
# Mod the values to prevent overflow, though not necessary for correctness
for s_new in range(3):
dp[k+1][s_new] %= MOD
# Now, compute the total using the prefix arrays and dynamic approach
total = 0
freq = defaultdict(int)
freq[(0, 0)] = 1 # initial state: count 0 ? and sum 0
for i in range(1, N+1):
current_cnt = prefix_cnt_q[i]
current_sum = prefix_sum[i]
temp = 0
# Iterate through all (c, s) in freq
for (c, s), cnt in freq.items():
k = current_cnt - c
if k < 0:
continue
t = (s - current_sum) % 3
if k > max_k:
ways = 0
else:
ways = dp[k][t]
temp += ways * cnt
total = (total + temp) % MOD
# Update freq with current state
freq_key = (current_cnt, current_sum)
freq[freq_key] += 1
print(total % MOD)
if __name__ == "__main__":
main()
gew1fw