Problem:


Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.



Sample input:
contest
son


Sample output:
10

Submission status: Wrong Answer

Solution code:
sl = list(input())
tl = list(input())

n = len(sl)
from collections import defaultdict
dic = defaultdict(list) 

for idx, s in enumerate(sl):
   dic[s].append(idx)
   dic[s].append(idx+n)

for s in dic:
   dic[s] = sorted(dic[s])

import bisect

ans = 1
now = 0
for t in tl:
   if dic[t] == []:
      print(-1)
      import sys
      sys.exit()
   idx = bisect.bisect_right(dic[t], now)
   ans += dic[t][idx] - now
   now = dic[t][idx]
   if now >= n:
      now -= n
print(ans)

Submission status: Wrong Answer

Solution code:
sl = list(input())
tl = list(input())

n = len(sl)
from collections import defaultdict
dic = defaultdict(list) 

for idx, s in enumerate(sl):
   dic[s].append(idx)
   dic[s].append(idx+n)

for s in dic:
   dic[s] = sorted(dic[s])

import bisect

ans = 1
now = 0
for t in tl:
   if dic[t] == []:
      print(-1)
      import sys
      sys.exit()
   idx = bisect.bisect(dic[t], now)
   ans += dic[t][idx] - now
   now = dic[t][idx]
   if now >= n:
      now -= n
print(ans)

Submission status: Wrong Answer

Solution code:
import bisect

S = list(map(str, input()))
T = list(map(str, input()))
len_S = len(S)
len_T = len(T)
ans = 0

dic = dict()

for i in range(len_S):
	if S[i] in dic:
		dic[S[i]].append(i)
	else:
		dic[S[i]] = [i]
		
cur = 0
flg = 0

for i in range(len_T):
	if not T[i] in dic:
		flg = 1
		break
	lst = dic[T[i]]
	new = bisect.bisect_left(lst, cur)
	# print(cur, lst[min(new, len(lst) - 1)])
	
	if new == len(lst) or lst[new] < cur:
		cur = lst[0]
		ans += len_S
		# print("reset")
	else:
		cur = lst[new]
	# print(T[i])
		
ans += cur + 1

if flg:
	print(-1)
elif ans <= len_S * (10 ** 100):
	print(ans)
else:
	print(-1)

Submission status: Wrong Answer

Solution code:
import bisect

S = list(map(str, input()))
T = list(map(str, input()))
len_S = len(S)
len_T = len(T)
ans = 0

dic = dict()

for i in range(len_S):
	if S[i] in dic:
		dic[S[i]].append(i)
	else:
		dic[S[i]] = [i]
		
cur = 0
flg = 0

for i in range(len_T):
	if not T[i] in dic:
		flg = 1
		break
	lst = dic[T[i]]
	new = bisect.bisect_left(lst, cur)
	# print(cur, lst[min(new, len(lst) - 1)])
	
	if new == len(lst) or lst[new] < cur:
		cur = lst[0]
		ans += len_S
		# print("reset")
	else:
		cur = lst[new]
	# print(T[i])
		
ans += cur + 1

if flg:
	print(-1)
else:
	print(ans)

Submission status: Wrong Answer

Solution code:
#dictでよかったかも？
import bisect

s=input()
t=input()

#a,b,cの出てきたところを小さい順にメモ
alp=[[] for i in range(26)]

for i in range(len(s)):
    alp[ord(s[i])-ord("a")].append(i)

#alp[w]の中からnow以降のものを探す．なければ一番手前を．
def bi_search(now,w):
    r=0
    if now>=alp[w][-1]:
        now=-1
        r=1
    ne_i=bisect.bisect_right(alp[w],now)
    ne=alp[w][ne_i]
    return ne,r

    
ans=0
rep=0
now=-1#s上の何文字目か
for i in range(len(t)):
    num=ord(t[i])-ord("a")
    if len(alp[num])==0:
        ans=-1
        break
    now,r=bi_search(now,num)
    rep+=r
if ans==-1:
    print(now)
else:
    ans=rep*len(s)+now+1
    print(ans)

Submission status: Wrong Answer

Solution code:
#dictでよかったかも？
import bisect

s=input()
t=input()

#a,b,cの出てきたところを小さい順にメモ
alp=[[] for i in range(26)]

for i in range(len(s)):
    alp[ord(s[i])-ord("a")].append(i)

#alp[w]の中からnow以降のものを探す．なければ一番手前を．
def bi_search(now,w):
    r=0
    if now>=alp[w][-1]:
        now=-1
        r=1
    ne_i=bisect.bisect_left(alp[w],now)
    ne=alp[w][ne_i]
    return ne,r

    
ans=0
rep=0
now=-1#s上の何文字目か
for i in range(len(t)):
    num=ord(t[i])-ord("a")
    if len(alp[num])==0:
        ans=-1
        break
    #print(num)
    now,r=bi_search(now,num)
    rep+=r
if ans==-1:
    print(now)
else:
    ans=rep*len(s)+now+1
    print(ans)

Submission status: Wrong Answer

Solution code:
#dictでよかったかも？
import bisect

s=input()
t=input()

#a,b,cの出てきたところを小さい順にメモ
alp=[[] for i in range(26)]

for i in range(len(s)):
    alp[ord(s[i])-ord("a")].append(i)

#alp[w]の中からnow以降のものを探す．なければ一番手前を．
def bi_search(now,w):
    r=0
    if now>alp[w][-1]:
        now=-1
        r=1
    ne_i=bisect.bisect_left(alp[w],now)
    ne=alp[w][ne_i]
    return ne,r

    
ans=0
rep=0
now=-1#s上の何文字目か
for i in range(len(t)):
    num=ord(t[i])-ord("a")
    if len(alp[num])==0:
        ans=-1
        break
    #print(num)
    now,r=bi_search(now,num)
    rep+=r
if ans==-1:
    print(now)
else:
    ans=rep*len(s)+now+1
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import bisect

d=defaultdict(list)

s=input()
t=input()

ns=len(s)
nt=len(t)

for i in range(ns):
  d[s[i]].append(i)

for k,v in d.items():
  d[k].append(ns)
#print(d)

ans=0
cnt=0

for i in range(nt):
  tt=d[t[i]]
  #print(t[i],tt,ans,cnt)
  if tt==[]:
    print(-1)
    exit(0)
  else:
    a=bisect.bisect_right(tt,cnt)
    if tt[a]==ns:
      ans+=ns+tt[0]-cnt
      cnt=tt[0]
      
    else:
      ans+=tt[a]-cnt
      cnt=tt[a]
      
print(ans+1)

Submission status: Wrong Answer

Solution code:
import bisect

S = input()
T = input()

ls = len(S)
d = {}
for i, s in enumerate(S):
  if s in d:
    d[s].append(i+1)
  else:
    d[s] = [i+1]

now = 0
ans = 0
pre_t = ''
for t in T:
  if not t in d:
    ans = -1
    break
    
  if t == pre_t:
    now += 1
  
  idx = bisect.bisect_left(d[t], now)
  if idx == len(d[t]):
    idx = 0
  
  if d[t][idx] > now:
    ans += d[t][idx] - now
  else:
    ans += ls + d[t][idx] - now
  
  now = d[t][idx]

print(ans)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()

pos = 0
itr = 0

S = set(s)
T = set(t)

if S>=T:
    for i in t:
        pos = s.find(i,pos) 
        if pos < 0:
            itr += 1
            pos = s.find(i)
        else:
            pos += 1
    print(itr*len(s)+pos)

else:
    print(-1)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()

pos = 0
itr = 0

S = set(s)
T = set(t)

if S>=T:
    for i in t:
        pos = s.find(i,pos) 
        if pos == -1:
            itr += 1
            pos = s.find(i)
        else:
            pos += 1
    print(itr*len(s)+pos)

else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**5)
input=lambda: sys.stdin.readline().rstrip()

def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=1

s=StoI()
t=StoI()
sn=len(s)
tn=len(t)

s*=2
dc=[[] for _ in range(26)]

for i in range(2*sn):
    dc[s[i]].append(i)

pr=0
for i in range(tn):
    nx=bisect.bisect(dc[t[i]],pr)
    if nx==len(dc[t[i]]):
        ans=-1
        break
    ans+=dc[t[i]][nx]-pr
    pr=dc[t[i]][nx]%sn

print(ans)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
d = {}
a = [None]*len(s)
for i in range(len(s))[::-1]:
    d[s[i]] = i
    a[i] = d.copy()
i = n = 0
for c in t:
    if c in a[i]:
        i = a[i][c]
    elif c in a[0]:
        i = a[0][c]
        n += 1
    else:
        print(-1)
        exit()
print(n*len(s)+i+1)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left as bl

S = input() * 2
T = input()
N = len(S) // 2

l = {}
for i in range(26):
  l[chr(ord("a") + i)] = []

for i in range(N*2):
  l[S[i]].append(i)

ans = N
for t in T:
  if not l[t]:
    print(-1)
    break
  cur = l[t][bl(l[t], ans%N+1)]
  ans = ans // N * N + cur
else:
  print(ans+1-N)

Submission status: Wrong Answer

Solution code:
from bisect import bisect as bs

S = input() * 2
T = input()
N = len(S) // 2

l = {}
for i in range(26):
  l[chr(ord("a") + i)] = []

for i in range(N*2):
  l[S[i]].append(i)

ans = N
for t in T:
  if not l[t]:
    print(-1)
    break
  cur = l[t][bs(l[t], ans%N)]
  ans = ans // N * N + cur
else:
  print(ans+1-N)

Submission status: Wrong Answer

Solution code:
from bisect import bisect as bs

S = input()
T = input()
N = len(S)

l = {}
for i in range(26):
  l[chr(ord("a") + i)] = []

for i in range(N):
  l[S[i]].append(i)

ans = 0
for t in T:
  if len(l[t]) == 0:
    print(-1)
    break
  cur = l[t][bs(l[t], ans%N) % len(l[t])]
  ans = ans // N * N + cur + (N if cur < ans % N else 0)
else:
  print(ans+1)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left as bl

S = input()
T = input()
N = len(S)

l = {}
for i in range(26):
  l[chr(ord("a") + i)] = []

for i in range(N):
  l[S[i]].append(i)

ans = 0
for t in T:
  if len(l[t]) == 0:
    print(-1)
    break
  cur = l[t][bl(l[t], ans%N) % len(l[t])]
  ans = ans // N * N + cur + (N if cur < ans % N else 0)
else:
  print(ans+1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect
def resolve():
    S=input()
    T=input()

    if(len(set(S))!=len(set(S+T))):
        print("-1")
        return

    idx=defaultdict(list)
    for i,s in enumerate(2*S):
        idx[s].append(i)

    now=0
    n=len(S)
    for t in T:
        i=bisect(idx[t],now%n)
        now+=idx[t][i]-now%n

    print(now+1)
resolve()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect
def resolve():
    S=input()
    T=input()
    n=len(S)

    if(not set(T)<=set(S)): # S には含まれない文字が T に存在するとき
        print("-1")
        return

    idx=defaultdict(list)
    for i,s in enumerate(2*S):
        idx[s].append(i)

    now=0
    for t in T:
        # now%n より大きい t を求める
        i=bisect(idx[t],now%n)
        now+=idx[t][i]-now%n

    print(now+1) # 1-indexed
resolve()

Submission status: Wrong Answer

Solution code:
# Library
alp = "abcdefghijklmnopqrstuvwxyz"
#

s = input()
t = input()
ss = s * 2
index = 0
next_char = [[-1 for j in range(len(s))] for i in range(26)]
# nc[i, j]: j文字目以降(1-indexed)で'a'+i がいつ出てくるか

for i in range(26):
    for j in range(len(s)):
        next_char[i][j] = ss.find(alp[i], j) - j

for i in range(len(t)):
    tmp = next_char[alp.index(t[i])][index % len(s)]
    if tmp < 0:
        index = -2
        break
    else:
        index += tmp

print(index + 1)

Submission status: Wrong Answer

Solution code:
s = list(input())
t = list(input())
def Strings_of_Impurity():
    for i in t:
        if not i in s:
            return -1
    ans = 0
    cnt = -1
    for i in t:
        tmp = s.index(i)
        if cnt < tmp:
            pass
        else:
            ans+=1
        cnt = tmp
    k = ans*len(s)+s.index(t[-1])+1
    if k >len(s)*(10**100):
        return -1
    else:
        return k

print(Strings_of_Impurity())

Submission status: Wrong Answer

Solution code:
s = list(input())
t = list(input())
def Strings_of_Impurity():
    for i in t:
        if not i in s:
            return -1
    ans = 0
    cnt = -1
    for i in t:
        tmp = s.index(i)
        if cnt < tmp:
            pass
        else:
            ans+=1
        cnt = tmp
    return ans*len(s)+s.index(t[-1])+1

print(Strings_of_Impurity())

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
a=-1
c=0
if set(t)>set(s):print(-1);exit()
for i in t:
  a=s.find(i,a+1)
  if a==-1:
    c+=1
    a=s.find(i)
print(c*len(s)+a+1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect_left
def resolve():
    S,T=input(),input()
    if(not set(S)>set(T)):
        print(-1)
        return

    E=defaultdict(list)
    for i,s in enumerate(2*S):
        E[s].append(i)

    n=len(S)
    ans=0
    now=0 # mod nで考える
    for t in T:
        i=bisect_left(E[t],now)
        ans+=E[t][i]-now+1
        now=(E[t][i]+1)%n
    print(ans)
resolve()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect_left
def resolve():
    S,T=input(),input()
    if(not set(S)>set(T)):
        print(-1)
        return

    E=defaultdict(list)
    for i,s in enumerate(2*S):
        E[s].append(i)

    n=len(S)
    ans=0
    now=0 # mod nで考える
    for t in T:
        i=bisect_left(E[t],now)
        ans+=E[t][i]-now+1
        now=E[t][i]%n+1
    print(ans)
resolve()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect
def resolve():
    S,T=input(),input()
    if(not set(S)>set(T)):
        print(-1)
        return

    E=defaultdict(list)
    for i,s in enumerate(2*S):
        E[s].append(i)

    n=len(S)
    ans=0
    now=-1 # mod nで考える
    for t in T:
        i=bisect(E[t],now)
        ans+=E[t][i]-now
        now=E[t][i]%n
    print(ans)
resolve()

Submission status: Wrong Answer

Solution code:
def main():
  import bisect
  s = input()
  t = input()
  al = [[] for _ in range(26)]
  for i in range(len(s)):
    al[ord(s[i])-97].append(i)
  #print(al)
  ans = 1
  std = 0
  for i in range(len(t)):
    x = al[ord(t[i])-97]
    if not x:
      print(-1)
      exit()
    y = bisect.bisect_left(x,std+1)
    if y == len(x):
      ans += len(s) - std + x[0]
      std = x[0]
    else:
      ans += al[ord(t[i])-97][y] - std 
      std = al[ord(t[i])-97][y]
  print(ans)
main()

Submission status: Wrong Answer

Solution code:
def main():
  import bisect
  s = input()
  t = input()
  al = [[] for _ in range(26)]
  for i in range(len(s)):
    al[ord(s[i])-97].append(i)
  #print(al)
  ans = 1
  s_length = len(s)
  std = 0
  for i in range(len(t)):
    x = al[ord(t[i])-97]
    if not x:
      print(-1)
      exit()
    y = bisect.bisect_left(x,std)
    if y == len(x):
      ans += len(s) - std + x[0]
      std = x[0]
    else:
      ans += al[ord(t[i])-97][y] - std 
      std = al[ord(t[i])-97][y]
  print(ans)
main()

Submission status: Wrong Answer

Solution code:
S = input()
T = input()
OUT = 10**5

N = len(S)
M = len(T)
indice = [0]*M

# 素直にやるとO(NM)かかるので工夫が必要
A = dict()
for i in range(26):
    l = chr(ord('a') + i)
    A[l] = []

# Sの文字がそれぞれ現れる場所を入れる
for i in range(N):
    A[S[i]].append(i+1)

for i in range(26):
    ai = chr(ord('a') + i)
    if len(A[ai]):
        A[ai] = [0, A[ai]]

for j in range(M):
    tj = T[j]
    if not len(A[tj]):
        print(-1)
        exit()
    idx, si = A[tj]
    indice[j] = si[idx%len(si)] + N * (idx//len(si))
    idx += 1
    A[tj][0] = idx
for i in range(1,M):
    if indice[i - 1] >= indice[i]:
        indice[i] += ((indice[i-1]-indice[i])//N+1)*N
print(indice[-1])

Submission status: Wrong Answer

Solution code:
S = input()
T = input()
OUT = 10**5

N = len(S)
M = len(T)
indice = [0]*M

# 素直にやるとO(NM)かかるので工夫が必要
A = dict()
for i in range(26):
    l = chr(ord('a') + i)
    A[l] = []

# Sの文字がそれぞれ現れる場所を入れる
for i in range(N):
    A[S[i]].append(i+1)

for i in range(26):
    ai = chr(ord('a') + i)
    if len(A[ai]):
        A[ai] = [0, A[ai]]

for j in range(M):
    tj = T[j]
    if not len(A[tj]):
        print(-1)
        exit()
    idx, si = A[tj]
    indice[j] = si[idx%len(si)] + N * (idx//len(si))
    idx += 1
    A[tj][0] = idx
for i in range(1,M):
    if indice[i - 1] >= indice[i]:
        indice[i] += ((indice[i-1]-indice[i])//N+1)*N
print(indice[-1])
print(indice)

Submission status: Wrong Answer

Solution code:
S = input()
T = input()
OUT = 10**5

N = len(S)
M = len(T)
indice = [0]*M

# 素直にやるとO(NM)かかるので工夫が必要
A = dict()
for i in range(26):
    l = chr(ord('a') + i)
    A[l] = []

# Sの文字がそれぞれ現れる場所を入れる
for i in range(N):
    A[S[i]].append(i+1)

for i in range(26):
    ai = chr(ord('a') + i)
    if len(A[ai]):
        A[ai] = [0, A[ai]]

for j in range(M):
    tj = T[j]
    if not len(A[tj]):
        print(-1)
        exit()
    idx, si = A[tj]
    indice[j] = si[idx%len(si)] + N * (idx//len(si))
    idx += 1
    A[tj][0] = idx
for i in range(1,M):
    if indice[i - 1] > indice[i]:
        indice[i] += ((indice[i-1]-indice[i])//N+1)*N
print(indice[-1])

Submission status: Wrong Answer

Solution code:
S = input()
T = input()
OUT = 10**5

N = len(S)
M = len(T)
indice = [0]*M

# 素直にやるとO(NM)かかるので工夫が必要
A = dict()
for i in range(26):
    a = ord('a')
    l = chr(a + i)
    A[l] = []

# S, T の文字がそれぞれ現れる場所を入れる
for i in range(N):
    A[S[i]].append(i)

for i in range(26):
    ai = chr(ord('a') + i)
    if len(A[ai]):
        A[ai].append(-len(A[ai]))

for j in range(M):
    tj = T[j]
    if not len(A[tj]):
        print(-1)
        exit()
    si = A[tj][0]
    if si < 0:
        for k in range(len(A[tj])):
            A[tj][k] = A[tj][k] + N
        indice[j] = A[tj][1]+1
    else:
        indice[j] = si+1
    A[tj] = A[tj][1:] + [si]

for i in range(1,M):
    if indice[i - 1] > indice[i]:
        indice[i] += ((indice[i-1]-indice[i])//N+1)*N
print(indice[-1])

Submission status: Wrong Answer

Solution code:
import bisect
s=input()
L=len(s)
s*=2
t=input()
pl={chr(i+97):[] for i in range(26)}
for i in range(len(s)):
  pl[s[i]]+=[i]
cnt=0
rem=0
for i in t:
  if pl[i]==[]:print(-1);exit()
  cnt+=pl[i][bisect.bisect_right(pl[i],rem)]-rem
  rem=cnt%L
print(cnt+1)

Submission status: Wrong Answer

Solution code:
import bisect
w1=input()
w2=input()
d={}
for i in list("qwertyuiopasdfghjklzxcvbnm"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
num=len(w1)
for i in w2:
  if d[i]==[]:
    print(-1)
    exit()
now=0#w1の何文字目か
count=0#w1を何回繰り返しているか
num2=len(w2)
for i in range(num2):
  d1=d[w2[i]]
  if d1[-1]<now:
    now=d1[0]
    count+=1
  else:
    index=bisect.bisect_left(d1,now)
    now=d1[index]
print(count*num+now)

Submission status: Wrong Answer

Solution code:
import bisect
S = list(input())
T = list(input())
s_dict = {}
# 二週分の文字とインデックス番号の組み合わせを保持
for s in S:
    s_dict[s] = []
for i, s in enumerate(S+S):
    bisect.insort_right(s_dict[s], i)

print(s_dict)
N = len(S)
try:
    ret = 0
    cnt = 0
    pre_t_idx = -1
    for t in T:
        t_idx = s_dict[t][bisect.bisect_right(s_dict[t], pre_t_idx)]
        if t_idx > N-1:
            cnt += 1
            t_idx -= N
        ret = t_idx+1
        pre_t_idx = t_idx

    print(cnt*N+ret)
except Exception as e:
    print(-1)

Submission status: Wrong Answer

Solution code:
import bisect
w1=input()
w2=input()
d={}
for i in list("abcdefghijklmnopqrstuvwxyz"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
b1=True
for i in range(len(w2)):
  if d[w2[i]]==[]:
    b1=False
    break
if not b1:
  print(-1)
else:
  count=0#何回w1を繰り返すか
  now=1#w1の何文字目を見てた？
  for i in w2:
    d1=d[i]
    if d1[-1]<now:
      count+=1
      now=d1[0]
    else:
      num=bisect.bisect_left(d1,now)
      now=d1[num]
  print(count*len(w1)+now)

Submission status: Wrong Answer

Solution code:
import bisect
w1=input()
w2=input()
d={}
for i in list("abcdefghijklmnopqrstuvwxyz"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
b=True
for i in range(len(w2)):
  if d[w2[i]]==[]:
    b=False
    break
if not b:
  print(-1)
else:
  count=0#何回w1を繰り返すか
  now=1#w1の何文字目を見てた？
  for i in w2:
    d1=d[i]
    if d1[-1]<now:
      count+=1
      now=d1[0]
    else:
      num=bisect.bisect_left(d1,now)
      now=d1[num]
  print(count*len(w1)+now)

Submission status: Wrong Answer

Solution code:
import bisect
w1=input()
w2=input()
d={}
for i in list("qwertyuiopasdfghjklzxcvbnm"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
b=True
for i in range(len(w2)):
  if d[w2[i]]==[]:
    b=False
    break
if not b:
  print(-1)
else:
  count=0#何回w1を繰り返すか
  now=1#w1の何文字目を見てる？
  for i in w2:
    d1=d[i]
    if d1[-1]<now:
      count+=1
      now=d1[0]
    else:
      num=bisect.bisect_left(d1,now)
      now=d1[num]
  print(count*len(w1)+now)

Submission status: Wrong Answer

Solution code:
import bisect
w1=input()
w2=input()
d={}
for i in list("qwertyuiopasdfghjklzxcvbnm"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
b=True
for i in range(len(w2)):
  if d[w2[i]]==[]:
    b=False
    break
if not b:
  print(-1)
else:
  count=0#何回w1を繰り返すか
  now=1#w1の何文字目
  for i in w2:
    d1=d[i]
    if d1[-1]<now:
      count+=1
      now=1
    num=bisect.bisect_left(d1,now)
    now=d1[num]
  print(count*len(w1)+now)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
import copy
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, T):

    si = defaultdict(deque)
    for i, s in enumerate(S):
        si[s].append(i)

    for k in si:
        si[k].append(-1)

    wsi = si
    used = defaultdict(deque)
    ans = 0
    i = -1
    for t in T:
        if t not in wsi:
            return -1
        j = wsi[t].popleft()
        used[t].append(j)
        if j > i:
            i = j
        else:
            ans += len(S)
            for k, q in used.items():
                while q:
                    wsi[k].appendleft(q.pop())
            i = wsi[t].popleft()
            used = defaultdict(deque)
            used[t].append(i)
    return ans + i + 1

def main():
    S = read_str()
    T = read_str()
    print(slv(S, T))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
import copy
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, T):

    si = defaultdict(deque)
    for i, s in enumerate(S):
        si[s].append(i)

    for k in si:
        si[k].append(-1)

    wsi = copy.deepcopy(si)
    used = defaultdict(deque)
    ans = 0
    i = -1
    for t in T:

        if t not in wsi:
            return -1
        j = wsi[t].popleft()
        used[t].append(j)
        if j > i:
            i = j
        else:
            ans += len(S)
            for k, q in used.items():
                while q:
                    wsi[k].appendleft(q.pop())
            i = wsi[t].popleft()
            used[t].append(i)
    return ans + i + 1

def main():
    S = read_str()
    T = read_str()
    print(slv(S, T))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, T):

    si = {}
    for i, s in enumerate(S):
        if s not in si:
            si[s] = i

    idx = []
    for t in T:
        if t in si:
            idx.append(si[t])
        else:
            return -1

    ans = 0
    for i in range(1, len(idx)):
        if idx[i-1] > idx[i]:
            ans += len(S)

    return ans + idx[-1] + 1


def main():
    S = read_str()
    T = read_str()
    print(slv(S, T))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, T):
    idx = []
    for t in T:
        for i, s in enumerate(S):
            if s == t:
                idx.append(i)
                break
        else:
            return -1

    ans = 0
    for i in range(1, len(idx)):
        if idx[i-1] > idx[i]:
            ans += len(S)

    return ans + idx[-1] + 1


def main():
    S = read_str()
    T = read_str()
    print(slv(S, T))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#%%

#%%
import bisect
s = list(input())
t = list(input())
alpha2num = lambda c: ord(c) - ord('a')
count = [0] * 26
count_t = [0] * 26
ind = [[] for _ in range(26)]
for i in range(len(s)):
    count[alpha2num(s[i])] += 1
    ind[alpha2num(s[i])].append(i)
for i in range(len(t)):
    count_t[alpha2num(t[i])] += 1

flag = True
for i in range(26):
    if count_t[i] >= 1 and count[i] == 0:
        flag = False

if flag:
    ans = 0
    tmp = 0
    i = 0
    while True:
        a = bisect.bisect_left(ind[alpha2num(t[i])], tmp)
        if 0 <= a < count[alpha2num(t[i])]:
            tmp = ind[alpha2num(t[i])][a]
            i += 1
        else:
            tmp = 0
            ans += 1
        if i >= len(t):
            break
    ans = ans * len(s) + tmp + 1
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from string import ascii_lowercase
from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x, c in enumerate(s):
    p[c].append(x)
z = 0
l = -1
for c in t:
    if c not in p:
        print(-1)
        break
    x = bisect_right(p[c],1)
    if x == len(p[c]):
        x = 0
        z += 1
    l = p[c][x]
else:
    print(z * len(s) + l + 1)

Submission status: Wrong Answer

Solution code:
from string import ascii_lowercase
from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x,c in enumerate(s):
    p[c].append(x)
z = 0
l = -1
for c in t:
    if c not in p:
        print(-1)
        break
    x = bisect_right(p[c],1)
    if x == len(p[c]):
        x = 0
        z += 1
    l = p[c][x]
else:
    print(z * len(s) + l + 1)