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:
s = input()
t = input()

s_len = len(s)
t_len = len(t)

n = [[] for i in range(28)]

def get_ord(c):
    return ord(c)-97

for i in range(s_len):
    ord_c = get_ord(s[i])
    n[ord_c].append(i)

#print(n)

#print("s_len",s_len)
#print("t_len",t_len)

def get_ans():
    res = 0
    for i in range(t_len):
        rr = res % s_len
        t_ord = get_ord(t[i])
        words = n[t_ord]
        if(len(words)==0):
            return -1
        if(words[len(words)-1]<=rr):
            res += s_len - rr 
            #print("add",s_len-rr)
            rr = res % s_len
        
        for w in words:
            if(rr < w):
                res += w - rr
                break
        #print(t[i],words,rr,res)
    
    return res+1

print(get_ans())

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_left

def sol():
    S = input()
    T = input()

    setS = set(S)
    setT = set(T)
    for t in setT:
        if not t in setS:
            print('-1')
            return

    posS = defaultdict(list)

    for i, s in enumerate(S):
        posS[s].append(i)
    for s in enumerate(S):
        posS[s].sort()

    prev = -1
    ans = 0
    N = len(S)

    for t in T:
        next = bisect_left(posS[t], prev)
        if next >= len(posS[t]):
            ans += N - prev
            ans += posS[t][0]
            prev = posS[t][0]
        else:
            ans += posS[t][next] - prev
            prev = posS[t][next]

    print(ans)


sol()

Submission status: Wrong Answer

Solution code:
s = str(input())
t = str(input())
l_s = len(s)
l_t = len(t)

x = s.find(t[0])
s.replace(t[0], "0", 1)

if x == -1:
    print(-1)
else:
    if l_t == 1:
        print(x)
    else:
        cnt = 0
        for i in range(1, l_t):
            y = s.find(t[i])
            if y == -1:
                print(-1)
                break
            else:
                s.replace(t[i], "0", 1)
                if x > y:
                    cnt += 1
                x = y
        print(l_s * cnt + x + 1)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_left, bisect, insort_left, insort
def solve():
    S = input()
    T = input()
    if not set(T) <= set(S):
        return -1
    len_s = len(S)
    m = defaultdict(list)
    for i, s in enumerate(S):
        m[s].append(i)
    for k, v in m.items():
        m[k].append(m[k][0] + len_s)
    last = -1
    ans = 0
    for t in T:
        num = bisect_left(m[t], last)
        ans += m[t][num] - last
        last = m[t][num] % len_s
    return ans
print(solve())

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
dic = {"a":[],"b":[],"c":[],"d":[],"e":[],"f":[],"g":[],"h":[],"i":[],"j":[],"k":[],"l":[],"m":[],"n":[],"o":[],"p":[],"q":[],"r":[],"s":[],"t":[],"u":[],"v":[],"w":[],"x":[],"y":[],"z":[]}
for i,c in enumerate(s):
    dic[c] += [i]
#print(dic)
cnt = 0
ind = -1
ans = 0
for c in t:
    d = dic[c]
    #print("c=",c,"d=",d)
    for i in d: #iは各文字のindex 昇順
    #    print("i=",i)
        if ind < i: #もし現在位置<iなら
            ind = i
   #         print("found, ind=",i)
            break
    else:
  #      print("not found")
        cnt += 1
        ind = -1
        # もう一度
        for j in d :  # jは各文字のindex 昇順
 #           print("2周目i=", i)
            if ind < j :  # もし現在位置<iなら
                ind = j
#                print("2周目found, ind=", j)
                break
        else:
#            print("!!!!!!!!!!!!!")
            ans = -1
            break
print((cnt*len(s)+(ind+1 if ind>0 else 0)) if ans > -1 else -1)

Submission status: Wrong Answer

Solution code:
from bisect import *
s=input()
t=input()
a=[[]for i in range(26)]
for i in range(len(s)):
    a[ord(s[i])-97].append(i+1)
p=-1
b=[len(i)for i in a]
r=0
for i in t:
    if b[ord(i)-97]==0:
        print(-1)
        break
    c=bisect_left(a[ord(i)-97],p)
    if c==b[ord(i)-97]:
        r+=1
        p=a[ord(i)-97][0]
    else:
        p=a[ord(i)-97][c]
else:
    print(r*len(s)+p)

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
ss=set(s)
tt=set(t)
tt <=ss
flag=0
if not tt<= ss:
    flag=1
if flag==1:
    print(-1)
else:
    ss=list(s)
    tt=list(t)
    l=len(ss)    
    count=0
    y=0
    for x in tt:
        ind=[i for i, xx in enumerate(ss) if xx == x]
       
        for z in ind:
#             print(ind, z, y)
            if z>=y:
                y=z
                flag=0
                break
            flag=1
        if flag==1:
            count+=1
            y=ind[0]
#         print(ind,count, z)
    ans=count*l+z+1
    print(ans)

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
u=[0]*len(t)
for i in range(len(t)):
    u[i]=s.find(t[i])+1
ans=u[0]
for i in range(1,len(t)):
    if u[i]>u[i-1]:
        ans+=u[i]-u[i-1]
    else:
        ans+=len(s)-u[i-1]+u[i]
print(-1 if 0 in u or ans>len(s)**10**100 else ans)

Submission status: Wrong Answer

Solution code:
from bisect import *

S = input()
T = input()

ds = {}
for i,s in enumerate(S) :
    if s not in ds :
        ds[s] = [i]
    else :
        ds[s].append(i)
L = []
ind = 0
for t in T :
    if t not in ds :
        ans = -1
        break
    
    if ind >= ds[t][-1] :
        ind = ds[t][0]
        L.append(ind)
    else :
        ind = ds[t][bisect_right(ds[t], ind)]
        L.append(ind)

    cnt = 0
    val = L[0]
    for i in range(1,len(L)) :
        if val >= L[i] :
            val = L[i]
            cnt += 1

    ans = cnt * len(S) + L[-1] + 1
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
from sys import exit,setrecursionlimit
import math
from collections import defaultdict,Counter,deque
from fractions import Fraction as frac

setrecursionlimit(1000000)


def main():
	s = input()
	t = input()
	sl = len(s)
	for i in t:
		if not i in s:
			print(-1)
			return
	l = defaultdict(list)
	for i in range(len(s)):
		l[s[i]].append(i)
	#print(l)
	c = 0
	for i in t:
		a = l[i]
		flag = True
		for j in a:
			if(c%sl < j):
				c += j-c%sl
				#print('Flag false')
				flag = False
				break
		if flag:
			c = math.ceil(c/sl) * sl + a[0]
		#print(i,c,a)
	print(c+1)

def zip(a):
	mae = a[0]
	ziparray = [mae]
	for i in range(1,len(a)):
		if(mae != a[i]):
			ziparray.append(a[i])
			mae = a[i]
	return ziparray

def is_prime(n):
	if n < 2: return False

	for k in range(2, int(math.sqrt(n)) + 1):
		if n % k == 0:
			return False

	return True

def list_replace(n,f,t):
	return [t if i==f else i for i in n]

def base_10_to_n(X, n):
	X_dumy = X
	out = ''
	while X_dumy>0:
		out = str(X_dumy%n)+out
		X_dumy = int(X_dumy/n)
	if(out == ''): return '0'
	return out

def gcd(l):
	x = l.pop()
	y = l.pop()
	while(x%y!=0):
		z = x%y
		x = y
		y = z
	l.append(min(x,y))
	return gcd(l) if len(l) > 1 else l[0]

class Queue():
	def __init__(self):
		self.q = deque([])
	def push(self,i):
		self.q.append(i)
	def pop(self):
		return self.q.popleft()
	def size(self):
		return len(self.q)
	def debug(self):
		return self.q

class Stack():
	def __init__(self):
		self.q = []
	def push(self,i):
		self.q.append(i)
	def pop(self):
		return self.q.pop()
	def size(self):
		return len(self.q)
	def debug(self):
		return self.q

class graph():
	def __init__(self):
		self.graph = defaultdict(list)
	def addnode(self,l):
		f,t = l[0],l[1]
		self.graph[f].append(t)
		self.graph[t].append(f)
	def rmnode(self,l):
		f,t = l[0],l[1]
		self.graph[f].remove(t)
		self.graph[t].remove(f)
	def linked(self,f):
		return self.graph[f]

class dgraph():
	def __init__(self):
		self.graph = defaultdict(set)
	def addnode(self,l):
		f,t = l[0],l[1]
		self.graph[f].append(t)
	def rmnode(self,l):
		f,t = l[0],l[1]
		self.graph[f].remove(t)
	def linked(self,f):
		return self.graph[f]

main()

Submission status: Wrong Answer

Solution code:
import bisect

def main():
    S = input()
    dS = {c : [] for c in 'abcdefghijklmnopqrstuvwxyz'}

    for i, s in enumerate(S):
        dS[s].append(i)

    #

    T = input()
    ans = 0

    p = 0

    for t in T:
        if not dS[t]:
            print(-1)
            return
        if dS[t][-1] < p:
            p = 0
            ans += len(S)
        idx = bisect.bisect_left(dS[t], p)
        p = dS[t][idx]
    
    print(ans + p + 1)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import bisect
s = input()
t = input()
N = len(s)
dict = {}
for i in range(N):
  if s[i] in dict.keys():
    dict[s[i]].append(i)
  else:
    dict[s[i]] = [i]
cur = 0
count = 1
for i in range(len(t)):
  if t[i] not in dict.keys():
    print(-1)
    exit()
  if cur <= dict[t[i]][-1]:
    tmp = bisect.bisect_left(dict[t[i]],cur)
    cur = dict[t[i]][tmp]
  else:
    count += 1
    cur = dict[t[i]][0]
#  print("t[i] {} count {}, cur {}".format(t[i],count,cur))
ans = (count-1)*N + cur + 1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

s = ns()
t = ns()
n = len(s)
g = {}

for i in range(n):
    if s[i] not in g:
        g[s[i]] = [i]
    else:
        g[s[i]].append(i)

import bisect

a = 0
b = -1
for i in t:
    if i not in g or a > n*(10**100):
        print(-1)
        exit()
    k = bisect.bisect_left(g[i],b)
    if k == len(g[i]):
        b = g[i][0]
        a += 1
    else:
        b = g[i][k]

print(n*a+b+1)

Submission status: Wrong Answer

Solution code:
A = input()
B = input()
exsi  = [0]*len(B)
a = 1
res = 0
now = 0
for i in range(len(A)):
  for j in range(len(B)):
    if(A[i] == B[j]):
      exsi[j] =1
for i in range(len(exsi)):
  a = a*exsi[i]
if(a == 0):
  res = -1  
Alength = len(A)*len(B)
newA = [0]*Alength

for i in range(len(newA)):
  newA[i] = A[i%len(A)]

if(res != -1):
  for i in range(len(B)):
    while(B[i] != newA[now]):
      now += 1
if(res != -1 ):     
  res = now + 1 
print(res)

Submission status: Wrong Answer

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

#print(t[0])

condition=0
for i in range(len(t)):
 if s.count(t[i])==0:
   condition=1
   break

if condition==1:
  print(-1)
else:
  j=0
  count=0
  while j <len(t)-1 and count<len(s)*(10**100):   
    for k in range(len(s)):
      count=count+1
      if t[j]==s[k]:
        j=j+1
        #print(j,k)
        if j==len(t):
          print(count)
          break
    if j==len(t):
      break
    if count == len(s)*(10**100):
      print(-1)
      break

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
s1=s
ans=0
flag=1
for i in t:
    if i not in s1:
        flag=0
if flag==0:
    print(-1)
else:
    for i in t:
        if i in s1:
            s1=s1[s1.index(i)+1:]
        else:
            s1=s[s.index(i)+1:]
            ans+=len(s)
    print(ans + s.index(i)+1)

Submission status: Wrong Answer

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

s_a = list(s*10)

i = 0
j = 0
while j <= len(t)-1:
  while not t[j] == s_a[i]:
    if i == len(s_a)-1:
      break
    i += 1
  j += 1
  
if i < len(s_a)-1:
  print(i+1)
elif i == len(s_a)-1 and s_a[i] == t[len(t)-1]:
  print(i+1)
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
# ABC138E - Strings of Impurity
import sys
input = sys.stdin.readline

def main():
    S, T = tuple(input() for _ in range(2))
    if not set(T) <= set(S):  # corner case
        print(-1)
        return
    lim_s, lim_t = len(S) - 1, len(T)
    ans, cur, idx = 1, 0, -1
    while cur < lim_t:
        find = S[idx + 1:].find(T[cur])
        if find == -1:
            ans += 1
            idx = -1
        else:
            idx += find + 1
            cur += 1
    print((ans - 1) * len(S) + idx + 1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import copy

s=list(input())
s_len=len(s)
t=list(input())
s_alphabets=[]
s_reference={}
ref_length=0
for i,alphabet in enumerate(s):
    s_alphabets.append(alphabet)
    s_reference.setdefault(alphabet,[]).append(i)
s_alphabets_set=set(s_alphabets)

copied_reference=copy.deepcopy(s_reference)
prev_checked=0
ans=0
flag=True
for i in t:
    if i not in s_alphabets_set:
        flag=False
        print(-1)
        break
    else:
        checked=copied_reference[i].pop(0)
        #print(i,checked)
        if copied_reference[i]==[]:
            #print('空っぽ')
            hoju=copy.copy(s_reference[i])
            copied_reference[i]=hoju
            #print("origin",s_reference)
            #print(copied_reference)
        if checked<prev_checked:
            ans+=s_len
        prev_checked=checked
if flag:
    print(ans+checked+1)

Submission status: Wrong Answer

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

alpha = [[] for _ in range(26)]
c2i = lambda x: ord(x) - ord('a')

for i, sl in enumerate(s):
    alpha[c2i(sl)].append(i)

pos = 0
count = 1
for tl in t:
    places = alpha[c2i(tl)]
    for place in places:
        if place > pos:
            count += place - pos
            pos = place
            break
    else:
        if len(places) == 0:
            print(-1)
            sys.exit()
        else:
            count += (len(s)-pos-1) + places[0] + 1
            pos = places[0]

print(count)

Submission status: Wrong Answer

Solution code:
#  --*-coding:utf-8-*--

import bisect

def f(D, T, lenOfS):
    x = 0
    p = 0
    for c in T:
        d = D[ord(c) - 97]
        if len(d) == 0:
            return -1
            
        idx = bisect.bisect_left(d, p)

        if idx < len(d):
            p2 = d[idx]
        else:
            p2 = d[0]
            x += lenOfS;

        x += (p2 - p)
        p = p2
            
    return x+1


def main():
    S = input()
    T = input()

    D = [[] for _ in range(26)]
    for i, c in enumerate(S):
        D[ord(c) - 97].append(i)

    print(f(D, T, len(S)))
    

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import bisect
s = input().rstrip()
t = input().rstrip()

a_ord = ord("a")
ch_place = [[] for _ in range(26)]
for i, ch in enumerate(s):
    ch_place[ord(ch) - a_ord].append(i)

# print(ch_place)

count = 0
idx = 0
for ch in t:
    ch_num = ord(ch) - a_ord
    if len(ch_place[ch_num]) == 0:
        print(-1)
        exit()
    place = bisect.bisect_right(ch_place[ch_num], idx)
    # print(ch_place[ch_num], idx, place)
    if place == len(ch_place[ch_num]):
        idx = ch_place[ch_num][0]
        count += 1
    else:
        idx = ch_place[ch_num][place]

# print(count, idx)
print(count * len(s) + idx + 1)

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
a=[]
import bisect
for i in range(len(s)):
	a.append([ord(s[i]),i])
a.sort()
c=[]
d=[]
for i in range(len(s)):
	c.append(a[i][0])
	d.append(a[i][1])
b=[]
e=[]
for i in range(len(t)):
	if c[0]<=ord(t[i])<=c[-1]:
		b.append(bisect.bisect_left(c,ord(t[i])))
	else:
		print(-1)
		exit()
for i in range(len(t)):
	e.append(d[b[i]])
ans=e[0]+1
for i in range(len(e)-1):
	if e[i]<e[i+1]:
		ans+=e[i+1]-e[i]
	else:
		ans+=len(s)-e[i]+e[i+1]
print(ans)

Submission status: Wrong Answer

Solution code:
import bisect
s=list(input())
t=list(input())
N=len(s)
sd={x:[] for x in sorted(set(s))}
if not set(t) <= set(sd.keys()):
    print(-1)
    exit()

for i,c in enumerate(s):
    sd[c].append(i)
index=0
ans=0
for c in t:
    i=bisect.bisect_left(sd[c],index+1)

    if i==len(sd[c]):
        ans+=1
        i=bisect.bisect_left(sd[c],0)
    index=sd[c][i]
print(ans*N+index+1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from bisect import bisect_left
from collections import defaultdict
INF = float("inf")


def solve(s: str, t: str):

    S = len(s)
    T = len(t)
    ABC = defaultdict(list)
    for i, c in enumerate(s):
        ABC[c].append(i)

    counter = 0
    curr = 0
    head = 0
    # print(ABC)
    while curr < T:
        if not ABC[t[curr]]:
            print(-1)
            return
        j = bisect_left(ABC[t[curr]], head+1)
        # print(curr, t[curr], ABC[t[curr]], j, head)
        if len(ABC[t[curr]]) == j:
            j = 0
        b = (ABC[t[curr]][j]-head) % S
        counter += b
        head = ABC[t[curr]][j]
        curr += 1
    print(counter+1)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
s=list(input())
t=list(input())
a=[[] for _ in range(len(t))]

for i in range(len(t)):
  for j in range(len(s)):
    if t[i]==s[j]:
      a[i].append(j)
    else:
      print('-1')
      sys.exit()

ans=0
cur=0
for i in range(len(t)-1):
  for j in range(len(a[i+1])):
    if a[i][cur]<a[i+1][j]:
      cur=j
      break
    if j==len(a[i+1])-1:
      ans+=len(s)
      cur=0
print(ans+1+a[-1][cur])

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict, deque

def main():
    input = sys.stdin.readline
    S = str(input().strip())
    T = str(input().strip())

    if not set(T) <= set(S):
        return -1

    n = len(S)
    d = defaultdict(deque)
    for i, s in enumerate(S, start=1):
        d[s].append(i)

    cnt = 0
    pos = 0
    for t in T:
        np = d[t].popleft()
        if np < pos:
            cnt += 1
        pos = np
        d[t].append(np)

    return n * cnt + pos


if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
import sys

s1 = input()
s2 = input()

n1 = 0
t1 = 0
t2 = -1

for i1 in range(len(s2) ):
    t1 =  s1.find(s2[i1])
    if t1 == -1:
        print(t1)
        sys.exit()
    if t1 == t2:
        n1 += len(s1)
    elif t1 > t2:
        n1 += t1 - t2
    else:
        n1 += t1 + (len(s1) - t2)
    t2 = t1

print(n1)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict
import bisect
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return sys.stdin.readline()[:-1]

def main():
    s = list(S())
    t = list(S())
    len_s = len(s)
    len_t = len(t)
    alfa = defaultdict(list)
    for i, c in enumerate(s):
        alfa[c].append(i)
    pre = 0
    ans = 0
    for i, c in enumerate(t):
        index = alfa[c]
        if len(index) == 0:
            print(-1)
            return
        a = bisect.bisect_right(index, pre)
        if a != len(index):

            pre = index[a]
        else:
            pre = index[0]
            ans += len(s)

    print(ans + pre + 1)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

def main(): 
    s = SI()
    t = SI()

    from collections import defaultdict
    s_dict = defaultdict(list)
    for i, char in enumerate(s):
        s_dict[char].append(i)

    # s_dict[char] には、 char が s の何番目に入っているかが記載されている。

    from bisect import bisect

    current_position = 0
    s_loops = 0
    for char in t:
        li = s_dict[char]
        if not li:
            print(-1)
            return
        # current_position より大きい最小の要素を二分探索で得る。
        pos = bisect(li, current_position)
        try:
            current_position = li[pos]
        except IndexError:
            # s は次のループに入った。
            s_loops += 1
            current_position = li[0]
        # print(current_position)
    print(len(s)*s_loops + current_position+1)



main()

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
ls,lt = len(s),len(t)
i = j = 0
si = lp = 0
while True:
    tc = t[i]
    si = s.find(tc)
    if si == -1:
        print(-1)
        exit(0)
    else:
        if i == lt-1:
            print(lp*ls + si+1)
            exit(0)
        else:
            while True:
                if t[i+1] in s[si+1:]:
                    si = s[si+1:].find(t[i+1]) + si
                    if i+1 == lt-1:
                        print(lp*ls + si+1)
                        exit(0)
                    else:
                        i+=1
                else:
                    i+=1
                    break
    lp += 1
    if i >= lt:
        print(-1)
        break

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right,bisect_left
alphabet_small = [chr(i) for i in range(97, 97+26)]
s = input()
t = input()
m = len(s)
n = len(t)

alpha = [[] for i in range(26)]
for i,let in enumerate(s):
    for j,al in enumerate(alphabet_small):
        if let == al:
            alpha[j].append(i)

#alpha　はsのどこに文字があるか

dp = [0 for i in range(n+1)] #i文字目までの最小
#求めるのはdp[n]
t_num = []
append = t_num.append
for let in t:
    for j,al in enumerate(alphabet_small):
        if let == al:
            t_num.append(j)

#t_num　はtの文字を数字に変換
now = -1
for i,let_num in enumerate(t_num):
    #print(i,let_num,alpha[let_num])
    if len(alpha[let_num]) == 0:
        print(-1)
        exit()
    else:
        q = bisect_left(alpha[let_num], now)
        if q != len(alpha[let_num]):
            next = alpha[let_num][q]
            #print(now,next,1)
            if now == next:
                dp[i+1] += m
                #print(dp[i+1])
            dp[i+1] += dp[i] + next - now
        else:
            next = alpha[let_num][0]
            dp[i+1] += dp[i] + next - now + m
        now = next



print(dp[n])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from bisect import bisect_left
from collections import defaultdict
INF = float("inf")


def solve(s: str, t: str):

    S = len(s)
    T = len(t)
    ABC = defaultdict(list)
    for i, c in enumerate(s):
        ABC[c].append(i)

    counter = 0
    curr = 0
    head = 0
    # print(ABC)
    while curr < T:
        if not ABC[t[curr]]:
            print(-1)
            return
        j = bisect_left(ABC[t[curr]], head)
        # print(curr, t[curr], ABC[t[curr]], j, head)
        if len(ABC[t[curr]]) == j:
            j = 0
        b = (ABC[t[curr]][j]-head) % S
        counter += b
        head = ABC[t[curr]][j]
        curr += 1
    print(counter+1)
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    t = next(tokens)  # type: str
    solve(s, t)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline


def main():
    s = input().strip()
    t = input().strip()

    ans = s.find(t[0])
    if ans < 0:
        print(-1)
        return

    prev = ans  # 直前に見つけた文字の位置
    j = 0  # t[j]まで見つけた
    i = ans

    while j < len(t)-1:
        ans += 1
        i = (i+1) % len(s)
        if i == prev:
            return print(-1)

        if s[i] == t[j+1]:
            j += 1
            prev = i

    print(ans+1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

s1 = input()
s2 = input()

n1 = 0
t1 = 0
t2 = 0

for i1 in range(len(s2) ):
    t1 =  s1.find(s2[i1])
    if t1 == -1:
        print(t1)
        sys.exit()
    if t1 == t2:
        n1 += len(s1)
    elif t1 > t2:
        if n1 == 0:
            n1 += t1 - t2 + 1
        else:
            n1 += t1 - t2
    else:
        n1 += t1 + (len(s1) - t2)
    t2 = t1

print(n1)

Submission status: Wrong Answer

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

#print(t[0])

condition=0
for i in range(len(t)):
 if s.count(t[i])==0:
   condition=1
   break

if condition==1:
  print(-1)
else:
  j=0
  count=0
  while j <len(t)-1 and count<len(s)*(10**100):   
    for k in range(len(s)):
      count=count+1
      if t[j]==s[k]:
        j=j+1
        #print(j,k)
        if j==len(t):
          print(count)
          break

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

s = ns()
t = ns()
g = {}

for i in range(len(s)):
    if s[i] not in g:
        g[s[i]] = [i]
    else:
        g[s[i]].append(i)

import bisect

a = 0
b = 0
for i in t:
    if i not in g:
        print(-1)
        exit()
    k = bisect.bisect_left(g[i],b)
    if k == len(g[i]):
        b = g[i][0]
        a += 1
    else:
        b = g[i][k]

print(len(s)*a+b+1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
import bisect
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    s = input()
    t = input()

    if not (set(t) <= set(s)):
        print(-1)
        return

    d = [[] for _ in range(26)]
    for i, j in enumerate(s):
        d[ord(j) - 97].append(i)

    i = 0
    c = 0
    for j in t:
        k = ord(j) - 97
        l = bisect.bisect_left(d[k], i)

        if l < len(d[k]):
            i = d[k][l]
        else:
            c += len(s)
            i = d[k][0]

    print(c + i + 1)

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

debug = True
debug = False

def dprint(*objects):
    if debug == True:
        print(*objects)

def main():
    s = SI()
    t = SI()

    d = {}
    for i, c in enumerate(s):
        if c not in d.keys():
            d[c] = [i]
        else:
            d[c].append(i)

    def init_didx():
        didx = {}
        for k in d.keys():
            didx[k] = 0
        return didx

    didx = init_didx()
    for c in set(t):
        if c not in d.keys():
            print(-1)
            return

    dprint(d)
    dprint(didx)

    i_loop = 0
    currentidx = -1
    for c in t:
        # 次の文字を読む
        poslist = d[c]

        if len(poslist) <= didx[c]:
            # 文字を取り切っている場合は次のループに
            i_loop += 1
            didx = init_didx()
            currentidx = poslist[0]
            didx[c] += 1
        else:
            # とり切っていない場合
            pos = poslist[didx[c]]

            if pos > currentidx:
                # 同じループでとれるなら取って、現在位置を更新
                currentidx = pos
                didx[c] += 1
            else:
                # いけないなら次のループでとったことにする
                i_loop += 1
                didx = init_didx()
                currentidx = poslist[0]
                didx[c] += 1

        dprint(c, i_loop, pos)

    print(len(s)*i_loop + currentidx + 1)

main()