結果

問題 No.3244 Range Multiple of 8 Query
ユーザー moon17
提出日時 2025-08-22 23:24:05
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 824 bytes
コンパイル時間 356 ms
コンパイル使用メモリ 82,232 KB
実行使用メモリ 88,800 KB
最終ジャッジ日時 2025-08-22 23:24:21
合計ジャッジ時間 9,902 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 17 TLE * 2 -- * 21
権限があれば一括ダウンロードができます

ソースコード

diff #

from bisect import*
from collections import*
n,q=map(int,input().split())
s=input()
e=[]
for i in range(1000):
  if i%8==0 and'0'not in str(i):
    e+=[*str(i)],
idx=defaultdict(list)
for i in range(n):
  idx[s[i]]+=i,
INF=1<<60
for _ in range(q):
  l,r=map(int,input().split())
  l-=1
  d=r-l
  m=min(d,3)
  ans=INF
  for nst in e:
    st=nst[:]
    if m!=len(st):
      continue
    p=defaultdict(int)
    a=0
    pos=r-1
    mv=[]
    while st:
      ns=st.pop()
      k=bisect(idx[ns],r-1)-1
      if 0<=k-p[ns]<len(idx[ns])and l<=idx[ns][k-p[ns]]:
        nxt=idx[ns][k-p[ns]]
        for t in mv:
          if t<idx[ns][k-p[ns]]:
            nxt-=1
        a+=abs(pos-nxt)
        mv+=idx[ns][k-p[ns]],
        p[ns]+=1
      else:
        a=INF
        break
      pos-=1
    ans=min(ans,a)
  print([-1,ans][ans<INF])
0