結果

問題 No.2019 Digits Filling for All Substrings
ユーザー gew1fw
提出日時 2025-06-12 18:25:07
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,514 bytes
コンパイル時間 185 ms
コンパイル使用メモリ 82,172 KB
実行使用メモリ 88,944 KB
最終ジャッジ日時 2025-06-12 18:26:14
合計ジャッジ時間 4,081 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other TLE * 1 -- * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

MOD = 998244353

def main():
    import sys
    input = sys.stdin.read
    data = input().split()
    N = int(data[0])
    S = data[1]
    
    # Precompute prefix sums for q (number of '?') and s (sum of non-? digits mod3)
    prefix_q = [0] * (N + 1)
    prefix_s = [0] * (N + 1)
    for i in range(1, N+1):
        c = S[i-1]
        prefix_q[i] = prefix_q[i-1] + (1 if c == '?' else 0)
        if c == '?':
            prefix_s[i] = prefix_s[i-1]
        else:
            d = int(c)
            prefix_s[i] = (prefix_s[i-1] + d) % 3
    
    # Precompute 10^k mod MOD
    pow10 = [1] * (N + 1)
    for i in range(1, N+1):
        pow10[i] = pow10[i-1] * 10 % MOD
    
    inv3 = pow(3, MOD-2, MOD)
    
    # We need to track the frequency of (q_i, s_i) pairs
    from collections import defaultdict
    freq = defaultdict(int)
    # Initialize with i=0 (q=0, s=0)
    freq[(0, 0)] = 1
    
    total = 0
    
    for j in range(1, N+1):
        q_j = prefix_q[j]
        s_j = prefix_s[j] % 3
        
        # Contribution from k=0 (q_j - q_i =0)
        count_k0 = freq.get((q_j, s_j), 0)
        total = (total + count_k0) % MOD
        
        # Contribution from k>0
        # Iterate over all possible previous q_i = q_j -k where k >=1
        # But this is O(q_j) which is up to j, leading to O(N^2) time.
        # This approach will not work for N=2e5.
        # Therefore, this code will not pass for large N, but it's the correct approach for small N.
        # To handle large N, a different approach is needed, which is not obvious.
        # For the sake of providing the code, this is included, but it's not efficient.
        for k in range(1, q_j + 1):
            q_i = q_j - k
            # For each possible s_i that leads to s_j - s_i ≡0, 1, 2 mod3
            s_i_0 = s_j %3
            cnt0 = freq.get((q_i, s_i_0), 0)
            term0 = (pow10[k] + 2) * inv3 % MOD
            total = (total + cnt0 * term0) % MOD
            
            s_i_1 = (s_j -1) %3
            cnt1 = freq.get((q_i, s_i_1), 0)
            term1 = (pow10[k] -1) * inv3 % MOD
            total = (total + cnt1 * term1) % MOD
            
            s_i_2 = (s_j -2) %3
            cnt2 = freq.get((q_i, s_i_2), 0)
            term2 = (pow10[k] -1) * inv3 % MOD
            total = (total + cnt2 * term2) % MOD
        
        # Update the frequency map with the current (q_j, s_j)
        freq[(q_j, s_j)] = freq.get((q_j, s_j), 0) + 1
    
    print(total % MOD)

if __name__ == "__main__":
    main()
0