結果

問題 No.464 PPAP
ユーザー mkawa2
提出日時 2020-04-30 15:00:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 498 ms / 2,000 ms
コード長 2,129 bytes
コンパイル時間 601 ms
コンパイル使用メモリ 82,644 KB
実行使用メモリ 77,568 KB
最終ジャッジ日時 2024-12-15 20:54:12
合計ジャッジ時間 3,187 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

# 偶数長、奇数長含めて回文「直径」(つまり全長)を返す
# s[i]の前の隙間を中心とした回文長がres[i*2](偶数長)
# s[i]を中心とした回文長がres[i*2+1](奇数長)
# si  0 1 2 3 4 5
# s   a b a a b a
# d  0103016103010
# di 0123456789...
# dummyがsに入っていないか注意
def Manacher(s):
    dummy="@"
    s = dummy + dummy.join(s) + dummy
    i=j=0
    res=[-1]*len(s)
    while i<len(s):
        while i-j>=0 and i+j<len(s) and s[i-j]==s[i+j]:j+=1
        res[i]=j-1
        k=1
        while i-k>=0 and k+res[i-k]+1<j:
            res[i+k]=res[i-k]
            k+=1
        i+=k
        j-=k
    return res

def main():
    s=SI()
    dd=Manacher(s)
    #print(dd)

    # 左にできるPPを長さごとに集計する
    cnt_pp=defaultdict(int)
    for i in range(1,len(s)-2):
        # i==dd[i]だと先頭から回文ができている
        if i==dd[i]:
            # 2つ目の回文長の限界
            lim=len(s)-i-2
            for j in range(i*2+1,lim+i*2+1):
                if j-i*2<=dd[j]:
                    # 2つの回文長の合計がi+j-2*i=j-i
                    cnt_pp[j-i]+=1
    #print(cnt_pp)

    # 右にできるPを長さごとにチェック
    dd.reverse()
    cnt_p=[0]*(len(s)+1)
    for i in range(1,len(dd)):
        if i==dd[i]:cnt_p[i]+=1
    #print(cnt_p)

    # 累積和をとって長さd以下のPがいくつあるかが分かるようにする
    for i in range(len(s)):cnt_p[i+1]+=cnt_p[i]
    #print(cnt_p)

    # 左のPPの長さが分かれば、右のPが何通りあるかが分かる
    # PPとPの組合せをすべて計算して答え
    ans=sum(c*cnt_p[len(s)-p-1] for p,c in cnt_pp.items())
    print(ans)

main()
0