結果

問題 No.1848 Long Prefixes
ユーザー chineristAC
提出日時 2022-02-18 23:20:42
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 172 ms / 2,000 ms
コード長 1,664 bytes
コンパイル時間 246 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 141,288 KB
最終ジャッジ日時 2024-06-29 09:53:09
合計ジャッジ時間 5,599 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 40
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd

input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())

mod = 10**9 + 7

def Z_algorithm(s):
    N = len(s)
    Z_alg = [0]*N

    Z_alg[0] = N
    i = 1
    j = 0
    while i < N:
        while i+j < N and s[j] == s[i+j]:
            j += 1
        Z_alg[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < N and k + Z_alg[k]<j:
            Z_alg[i+k] = Z_alg[k]
            k += 1
        i += k
        j -= k
    return Z_alg

N = int(input())
A = li()
S = input()
S = [ord(s)-ord("a") for s in S]

B = [A[0]]
T = [S[0]]
for i in range(1,N):
    if T[-1]==S[i]:
        B[-1] += A[i]
    else:
        B.append(A[i])
        T.append(S[i])

n = len(B)
if n==1:
    exit(print((B[0]*(B[0]+1)//2) % mod))
ZB = Z_algorithm(B[1:])
ZT = Z_algorithm(T[1:])

imos = [B[i] for i in range(n)]
for i in range(1,n):
    imos[i] += imos[i-1]

res = 0
for i in range(n):
    if T[i]!=T[0]:
        continue
    
    if B[i] < B[0]:
        res += B[i] * (B[i]+1)//2
        continue
    
    res += B[0] * (B[0]-1)//2 + B[0] * (B[i]-B[0])
    if i==n-1:
        res += B[0]
        continue

    k_b,k_t = ZB[i],ZT[i]
    k = min(k_b,k_t)
    if i+k==n-1:
        res += B[0] + imos[n-1] - imos[i]
    else:
        if T[k+1]!=T[i+k+1]:
            res += B[0] + imos[i+k] - imos[i]
        else:
            res += B[0] + imos[i+k] - imos[i] + min(B[k+1],B[i+k+1])
    
print(res % mod)



        

0