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:
# -*- coding: utf-8 -*-
from string import ascii_lowercase

def lower_bound(al, key):
    """
    一般に左側が満たしておらず、右側は満たしている判定基準(境目は一つ)ならlower_boundになる
    (条件を満たすもののうち、最小のインデックスを返す)
    単調にさえなっていれば、左右が逆になっていても検索には使える(ng/okも一緒に逆にする必要がある)
    """
    def isOk(a):
        # alの中でkey以上のアイテムのうち最小のインデックスを返す
        # upper_boundにする時にはa>key
        return a>=key

    ng = -1
    ok = len(al)
    if ok==0:
        return -1
    while abs(ok-ng)>1:
        mid = (ok+ng)//2

        if isOk(al[mid]):
            ok = mid
        else:
            ng = mid
    return ok


def f(s,t):
    n = len(s)
    s += s

    d = {}
    for c in ascii_lowercase:
        d[c] = []

    for i in range(2*n):
        d[s[i]].append(i)


    m = len(t)
    idx = 0
    for i in range(m):
        c = lower_bound(d[t[i]],idx%n)
        if c>=0:
            idx += d[t[i]][c] - idx%n
        else:
            return -1

    return idx+1

if __name__ == '__main__':
    s = input()
    t = input()
    print(f(s,t))

Submission status: Wrong Answer

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

for i in range(len(t)):
    if s.find(t[i])==-1:
        print(-1)
        break
else:
    a=0
    count=0
    for k in t:
        if k in s[a:]:
            a=s.find(k)+1
        else:
            count+=1
            a=s.find(k)+1
    print(count*len(s)+a)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
alphabet_num = 26
double_s = s+s
len_s = len(s)
next_step = []
for i in range(len_s):
    next_step_same_alphabet = [-1]*alphabet_num
    for alphabet in range(alphabet_num):
        for j in range(i+1,len_s*2):
            if alphabet == ord(double_s[j])-ord('a'):
                next_step_same_alphabet[alphabet] = j-i
                break
            else:
                continue
    next_step.append(next_step_same_alphabet)
count = 0
place_now = 0
if t[0] != s[0]:
    count += 1
for i in range(len(t)):
    if next_step[place_now][ord(t[i])-ord('a')]  > 0:
        count += next_step[place_now][ord(t[i])-ord('a')]
        place_now += next_step[place_now][ord(t[i])-ord('a')]
        if place_now >= len_s:
            place_now = place_now - len_s
    else:
        count = -1
        break
print(count)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
alphabet_num = 26
double_s = s+s
len_s = len(s)
next_step = []
for i in range(len_s):
    next_step_same_alphabet = [-1]*alphabet_num
    for alphabet in range(alphabet_num):
        for j in range(i+1,len_s*2):
            if alphabet == ord(double_s[j])-ord('a'):
                next_step_same_alphabet[alphabet] = j-i
                break
            else:
                continue
    next_step.append(next_step_same_alphabet)
count = 0
place_now = 0
if t[0] != s[0]:
    count += 1
for i in range(len(t)):
    if next_step[place_now][ord(t[i])-ord('a')]  > 0:
        count += next_step[place_now][ord(t[i])-ord('a')]
        place_now += next_step[place_now][ord(t[i])-ord('a')]
        if place_now >= len_s:
            place_now = place_now - len_s
    else:
        count = -1
        break
print(count)

Submission status: Wrong Answer

Solution code:
s = input()
t = input()
alphabet_num = 26
double_s = s+s
len_s = len(s)
next_step = []
for i in range(len_s):
    next_step_same_alphabet = [-1]*alphabet_num
    for alphabet in range(alphabet_num):
        for j in range(i+1,len_s*2):
            if alphabet == ord(double_s[j])-ord('a'):
                next_step_same_alphabet[alphabet] = j-i
                break
            else:
                continue
    next_step.append(next_step_same_alphabet)
print(next_step)
count = 1
place_now = 0
for i in range(len(t)):
    if next_step[place_now][ord(t[i])-ord('a')]  > 0:
        count += next_step[place_now][ord(t[i])-ord('a')]
        place_now += next_step[place_now][ord(t[i])-ord('a')]
        if place_now >= len_s:
            place_now = place_now - len_s
    else:
        count = -1
        break
print(count)

Submission status: Wrong Answer

Solution code:
s = list(str(input()))
s_pri = s.copy()
m = len(s)
t = list(str(input()))
n = len(t)
ans = 0
k = 0
while k < n:
    tk = t[k]
    if not tk in s:
        print('-1')
        break
    else:
        if k != n-1 and tk in s_pri:
            a = s_pri.index(tk) + 1
            del s_pri[:a]
        elif k != n-1 and not tk in s_pri:
            ans += m
            s_pri = s.copy()
            a = s_pri.index(tk) + 1
            del s_pri[:a]
        elif k == n-1:
            if tk in s_pri:
                a = s_pri.index(tk) + 1
                m_pri = m - len(s_pri) + a
                ans += m_pri
            else:
                m_pri = s.index(tk) + 1
                ans += m_pri
            print(ans)
        k += 1

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left


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

    table = {ss: [] for ss in set(s)}
    for i, ss in enumerate(s):
        table[ss].append(i)

    cnt = 1
    cur = -1
    for tt in t:
        if tt not in table:
            print(-1)
            return
        tl = table[tt]
        idx = bisect_left(tl, cur)
        if idx == len(tl):
            idx = 0
            cnt += 1
        cur = tl[idx]
    print(len(s) * (cnt - 1) + cur + 1)


main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left


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

    table = {ss: [] for ss in set(s)}
    for i, ss in enumerate(s):
        table[ss].append(i)

    cnt = 1
    cur = -1
    for tt in t:
        if tt not in table:
            print(-1)
            return
        tl = table[tt]
        idx = bisect_left(tl, cur)
        if idx == len(tl) or tl[idx] <= cur:
            idx = 0
            cnt += 1
        cur = tl[idx]
    print(len(s) * (cnt - 1) + cur + 1)


main()

Submission status: Wrong Answer

Solution code:
from collections import*
from bisect import*

s=input()
t=input()
slen=len(s)
d=defaultdict(list)

for i,c in enumerate(s):
    d[c].append(i)

nowplace=0
roop=0
for c in t:
    if not d[c]:
        print(-1)
        exit()
    i=bisect(d[c],nowplace)
    if len(d[c])==i:
        roop+=1
        nowplace=d[c][0]
    else:
        nowplace=d[c][i]

print(roop*slen+nowplace+1)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left


def main():
    s = list(input())
    t = list(input())
    nt = len(t)

    table = {ss: [] for ss in set(s)}
    for i, ss in enumerate(s):
        table[ss].append(i)

    cnt = 1
    cur = 0
    for i in range(nt):
        tt = t[i]
        if tt not in table:
            print(-1)
            return
        tl = table[tt]
        idx = bisect_left(tl, cur)
        if idx >= len(tl) or tl[idx] <= cur:
            idx = 0
            cnt += 1
        cur = tl[idx]
    print(len(s) * (cnt - 1) + cur + 1)


main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_right


def main():
    s = input()
    t = input()
    N = len(s)
    idx = defaultdict(list)
    for i in range(N):
        c = s[i]
        idx[c].append(i)
    pos = 0
    ans = 0
    for c in t:
        if c not in idx:
            print(-1)
            return
        n = bisect_right(idx[c], pos)
        if n == len(idx[c]):
            ans += N - pos + idx[c][0]
            pos = idx[c][0]
        else:
            ans += idx[c][n] - pos
            pos = idx[c][n]
    print(ans+1)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import bisect

S = input()
T = input()

d = [[] for _ in range(27)]
alpha2num = lambda c: ord(c) - ord("a") + 1

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

idx = 0
ans = 1
for t in T:
    dl = d[alpha2num(t)]
    if not(dl):
        ans = -1
        break
    insert_idx = bisect.bisect_right(dl, idx)
    if insert_idx == len(dl):
        ans += (len(S) - idx + dl[0])
        idx = dl[0]
    else:
        ans += (dl[insert_idx] - idx)
        idx = dl[insert_idx]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

def search_list_position(*list,last):
    for i in range(len(list)):
        if last<i:
            p=i
        elif i==len(list)-1:
            p=0
    return p


s=input()
t=input()
for i in t:
    if i not in s:
        print("-1")
        sys.exit()

count=[[] for i in range(26)]
slen=len(s)
for i in range(slen):
    count[ord(s[i])-97]+=[i]

l=0
ans=0

for i in t:
    c=ord(i)-97
    q=search_list_position(*count[c],last=l)
    if count[c][q]<l:
        ans+=slen-l+count[c][q]
    else:
        ans+=count[c][q]-l
    l=count[c][q]

print(ans+1)

Submission status: Wrong Answer

Solution code:
import sys


def search_list_position(*list,last):
    for i in range(len(list)):
        if last<i:
            p=i
        elif i==len(list)-1:
            p=0
    return p


s=input()
t=input()
for i in t:
    if i not in s:
        print("-1")
        sys.exit()

count=[[] for i in range(26)]
slen=len(s)
for i in range(slen):
    count[ord(s[i])-97]+=[i]

l=0
ans=0

for i in t:
    c=ord(i)-97
    q=search_list_position(*count[c],last=l)
    if count[c][q]<l:
        ans+=slen-l+count[c][q]
        print(slen-l+count[c][q])
    else:
        ans+=count[c][q]-l
        print(count[c][q]-l)
    l=count[c][q]

print(ans+1)

Submission status: Wrong Answer

Solution code:
from pprint import pprint
import sys

s = sys.stdin.readline().strip()
t = sys.stdin.readline().strip()

s_set = set()
for s_i in s:
    s_set.add(s_i)
t_set = set()
for t_i in t:
    t_set.add(t_i)

if not s_set >= t_set:
    print(-1)
    sys.exit()

t_index = {}
for t_i in t_set:
    t_index[t_i] = [i for i, s_i in enumerate(s) if s_i == t_i]
# pprint(t_index)

s_len = len(s)

ans = 0
tmp = [0]
for t_i in t:
    tmp = [p + s_len * ((ans + p) // s_len) for p in t_index[t_i]]
    # pprint(tmp)
    ans = min(tmp) + 1
    # print(t_i, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify, heapreplace
from collections import defaultdict
from bisect import bisect_left


class Solution:
    def main(self):
        s = input()
        t = input()
        n = len(s)
        m = len(t)
        charpos = defaultdict(list)
        for i in range(n):
            charpos[s[i]].append(i)

        maps = {}
        for key in charpos.keys():
            values = charpos[key] + [n]
            st = idx = 0
            res = [0] * n
            while st < n:
                if idx < len(values) and st >= values[idx]:
                    idx += 1
                if values[idx] == n:
                    res[st] = values[0]
                else:
                    res[st] = values[idx]
                st += 1

            while st < n:
                res[st] = values[-1]
                st += 1
            maps[key] = res

        # print(maps)

        crrpos = -1
        loop = 0
        for j in range(m):
            if t[j] not in charpos:
                print(-1)
                return
            else:
                if crrpos > maps[t[j]][crrpos]:
                    loop += 1
                crrpos = maps[t[j]][crrpos]

        print(loop * n + crrpos + 1)


if __name__ == '__main__':
    Solution().main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify, heapreplace
from collections import defaultdict
from bisect import bisect_left


class Solution:
    def main(self):
        s = input()
        t = input()
        n = len(s)
        m = len(t)
        charpos = defaultdict(list)
        for i in range(n):
            charpos[s[i]].append(i)

        maps = {}
        for key in charpos.keys():
            values = charpos[key]
            st = idx = 0
            res = [0] * n
            while st <= values[-1]:
                if st > values[idx]:
                    idx += 1
                res[st] = values[idx]
                st += 1
            while st < n:
                res[st] = values[-1]
                st += 1
            maps[key] = res

        # print(maps)

        crrpos = -1
        loop = 0
        for j in range(m):
            if t[j] not in charpos:
                print(-1)
                return
            else:
                if crrpos >= maps[t[j]][crrpos]:
                    loop += 1
                crrpos = maps[t[j]][crrpos]

        print(loop * n + crrpos + 1)


if __name__ == '__main__':
    Solution().main()

Submission status: Wrong Answer

Solution code:
s  = input()
t  = input()
ps = {}

for i in range(0, len(s)):
	if i < len(s) - 1:
		ss = s[i : i + 2]
		if ss in ps:
			ps[ss].append(i)
		else:
			ps[ss] = [i]
	c = s[i]
	if c in ps:
		ps[c].append(i)
	else:
		ps[c] = [i]
		
a = 0
b = -1
f = False
i = 0

while i < len(t):
	f  = False
	ss = t[i : i + 2]
	if ss in ps and len(ss) == 2:
		for p in ps[ss]:
			if b < p:
				b = p + 1
				f = True
				break
		if f == False:
			a += 1
			b  = ps[ss][0] + 1
		i += 2
	else:
		c = t[i]
		if c not in ps:
			break
		for p in ps[c]:
			if b < p:
				b = p
				f = True
				break
		if f == False:
			a += 1
			b  = ps[c][0]
		i += 1
	f = True
	
if f == False:
	print(-1)
else:
	print(a * len(s) + b + 1)

Submission status: Wrong Answer

Solution code:
s  = input()
t  = input()
ps = {}

for i in range(0, len(s)):
	c = s[i]
	if c in ps:
		ps[c].append(i)
	else:
		ps[c] = [i]
		
a = 0
b = -1
f = False

for c in t:
	f = False
	if c not in ps:
		break
	i = (b + 1) % len(s)
	if c == s[i]:
		if i < b:
			a += 1
			b  = 0
		else:
			b += 1
	else:
		for p in ps[c]:
			if b < p:
				b = p
				f = True
				break
		if f == False:
			a += 1
			b  = ps[c][0]
	f = True
	
if f == False:
	print(-1)
else:
	print(a * len(s) + b + 1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(1000000)


def main():
  originalStr = input()
  target = input()

  blContain = False
  for char in list(target):
    if char not in list(originalStr):
      blContain = False
      break
    blContain = True
  
  if not blContain:
    print("-1")
    return

  count = 0
  bl_list = []

  j=0
  target_char = list(target)[j]

  while True:
    for char in list(originalStr):
      count += 1
      if char == target_char:
        bl_list.append(True)
      
        if len(bl_list) == len(target):
          print(count)
          return

        j += 1
        target_char = list(target)[j]
  return

main()

Submission status: Wrong Answer

Solution code:
s  = input()
t  = input()
ps = {}

for i in range(0, len(s)):
	c = s[i]
	if c in ps:
		ps[c].append(i)
	else:
		ps[c] = [i]
		
a = 0
b = -1
f = False

for c in t:
	f = False
	if c not in ps:
		break
	i = (b + 1) % len(s)
	if c == s[i]:
		if i < b:
			a += 1
			b  = 0
		else:
			b += 1
	else:
		for p in ps[c]:
			if b < p:
				b = p
				break
		if f == False:
			a += 1
			b  = ps[c][0]
	f = True
	
if f == False:
	print(-1)
else:
	print(a * len(s) + b + 1)

Submission status: Wrong Answer

Solution code:
from bisect import bisect

s = input()
t = input()

indices = {}
N = len(s)
for i in range(N):
  try:
    indices[s[i]].append(i)
  except:
    indices[s[i]] = [i]

min_i = 0
cur = 0
for i in range(len(t)):
  try:
    idx = bisect(indices[t[i]], cur)
    try:
      n = indices[t[i]][idx]
    except:
      n = indices[t[i]][0]

    if n <= cur:
      min_i += (N - cur) + n
    else:
      min_i += (n - cur)
    cur = n
  except:
    print(-1)
    break
else:
  print(min_i + 1)

Submission status: Wrong Answer

Solution code:
s  = input()
t  = input()
ps = {}

for i in range(0, len(s)):
	c = s[i]
	if c in ps:
		ps[c].append(i)
	else:
		ps[c] = [i]
		
a = 0
b = -1

for c in t:
	if c not in ps:
		break
	f = False
	for p in ps[c]:
		if b < p:
			b = p
			f = True
			break
	if f == False:
		a += 1
		b  = ps[c][0]
	
if b == -1:
	print(-1)
else:
	print(a * len(s) + b + 1)

Submission status: Wrong Answer

Solution code:
import sys

s = input()
t = list(input())

string = s
length = 1

for i in t:
	if s.find(i)==-1:
		print(-1)
		sys.exit()
	if string.find(i)==-1:
		string = string + s
		length += 1
	string = string[string.find(i) : ]
	
print(length*len(s)-len(string)+1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7
alp=string.ascii_lowercase
d_al=dict([(i,j) for j,i in enumerate(alp)])

s=[d_al[i] for i in input()]
t=[d_al[i] for i in input()]
Ss=set(s)
St=set(t)
ns=len(s)
nt=len(t)
ss=s*2
#print(ss)

g=[{} for _ in range(ns)]
pos=[-1]*26
for i in range(ns*2)[::-1]:
    for j in Ss:
        if i<ns:
            g[i][j]=pos[j]-i
    pos[ss[i]]=i
#for i in range(len(g)):
#    print(g[i])

if len(St-Ss)!=0:
    ans=-1
else:
    cur=0
    cur+=g[-1][t[0]]-1
    #print(cur)
    for i in range(1,nt):
        print(cur,s[cur%ns],'tg=',t[i],g[cur%ns][t[i]])
        cur+=g[cur%ns][t[i]]
    ans=cur+1
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7
alp=string.ascii_lowercase
d_al=dict([(i,j) for j,i in enumerate(alp)])

s=[d_al[i] for i in input()]
t=[d_al[i] for i in input()]
Ss=set(s)
St=set(t)
ns=len(s)
nt=len(t)
ss=s*2
#print(ss)

g=[{} for _ in range(ns)]
pos=[-1]*26
for i in range(ns*2)[::-1]:
    for j in Ss:
        if i<ns:
            g[i][j]=pos[j]-i
    pos[ss[i]]=i
#for i in range(len(g)):
#    print(g[i])

if len(St-Ss)!=0:
    ans=-1
else:
    cur=0
    cur+=g[-1][t[0]]
    cur%=ns
    for i in range(1,nt):
        #print(cur,s[cur],'tg=',t[i],g[cur][t[i]])
        cur+=g[cur%ns][t[i]]
    ans=cur+1
print(ans)#,loop,has)

Submission status: Wrong Answer

Solution code:
abc=list(map(chr,range(97,123)))

s=input()
t=input()
for x in abc:
    if x in t and x not in s:
        print(-1)
        exit()
l=[[0]*len(s) for _ in [0]*26]
j=0
for x in abc:
    if x in s and x in t:
        f=s.find(x)
        k=-1
        for i in range(len(s)-1,-1,-1):
            l[j][i]=k if k>=0 else f
            if s[i]==x:k=i
    j+=1
c=0
i=0
j=0
while j<len(t):
    k=l[abc.index(t[j])][i]
    if k<=i:c+=1
    i=k
    j+=1
print(c*len(s)+k+1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7
alp=string.ascii_lowercase
d_al=dict([(i,j) for j,i in enumerate(alp)])

s=[d_al[i] for i in input()]
t=[d_al[i] for i in input()]
Ss=set(s)
St=set(t)
ns=len(s)
nt=len(t)
ss=s*2

g=[{} for _ in range(ns)]
pos=[-1]*26
for i in range(ns*2)[::-1]:
    for j in Ss:
        if i<ns:
            g[i][j]=pos[j]-i
    pos[ss[i]]=i

if len(St-Ss)!=0:
    ans=-1
else:
    ans=1
    cur=0
    for i in range(nt):
        ans+=g[cur][t[i]]
        cur+=g[cur][t[i]]
        cur%=ns
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7
alp=string.ascii_lowercase
d_al=dict([(i,j) for j,i in enumerate(alp)])

s=[d_al[i] for i in input()]
t=[d_al[i] for i in input()]
Ss=set(s)
St=set(t)
ns=len(s)
nt=len(t)
ss=s*2
#print(ss)

g=[{} for _ in range(ns)]
pos=[-1]*26
for i in range(ns*2)[::-1]:
    for j in Ss:
        if i<ns:
            g[i][j]=pos[j]-i
    pos[ss[i]]=i
#for i in range(len(g)):
#    print(g[i])

if len(St-Ss)!=0:
    ans=-1
else:
    ans=0
    cur=0
    for i in range(nt):
        ans+=g[cur][t[i]]
        cur+=g[cur][t[i]]
        cur%=ns
print(ans)#,loop,has)

Submission status: Wrong Answer

Solution code:
abc=list(map(chr,range(97,123)))

s=input()
t=input()
for x in abc:
    if x in t and x not in s:
        print(-1)
        exit()
l=[[0]*len(s) for _ in [0]*26]
j=0
for x in abc:
    if x in s and x in t:
        f=s.find(x)
        k=-1
        for i in range(len(s)-1,-1,-1):
            if s[i]==x:k=i
            l[j][i]=k if k>=0 else f
    j+=1
c=0
i=0
j=0
while j<len(t):
    k=l[abc.index(t[j])][i]
    if k<=i:c+=1
    i=k
    j+=1
print(c*len(s)+k+1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7

s=input()
t=input()
s=list(s)
t=list(t)
Ss=set(s)
St=set(t)
n=len(s)

alp=string.ascii_lowercase
di=dict([(i,j) for j,i in enumerate(alp)])
#print(di)
g=[{} for _ in range(n)]
fp=[10*10 for i in range(26)]
lp=[-1 for i in range(26)]

for i,c in enumerate(s):
    fp[di[c]]=min(i,fp[di[c]])
    for next_c in [di[l] for l in Ss]:
        if fp[next_c]!=-1:
            g[i][next_c]=(fp[next_c],1)

for i in range(n)[::-1]:
    for next_c in [di[l] for l in Ss]:
        if lp[next_c]!=-1:
            g[i][next_c]=(lp[next_c],1 if i==lp[next_c] else 0)
    lp[di[s[i]]]=i

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


#print(Ss,St,St-Ss)
if len(St-Ss)!=0:
    ans=-1
else:
    loop=0
    has=0
    st=di[t[0]]
    loop+=g[0][st][1]
    i_n=g[0][st][0]
    has=i_n
    for i in range(1,len(t)):
        ch=di[t[i]]
        loop+=g[i_n][ch][1]
        i_n=g[i_n][ch][0]
        has=g[i_n][ch][0]
        #print(loop,has,i_n,g[i_n][ch])
    ans=loop*n+has+1
print(ans)#,loop,has)
#print([[i,di[i]] for i in s])
'''
for i in g:
    print(sorted(list(i.items()),key=lambda x:x[0]))
'''

Submission status: Wrong Answer

Solution code:
abc=list(map(chr,range(97,123)))

s=input()
t=input()
for x in abc:
    if x in t and x not in s:
        print(-1)
        exit()
l=[[0]*len(s) for _ in [0]*26]
j=0
for x in abc:
    if x in s and x in t:
        f=s.find(x)
        k=-1
        for i in range(len(s)-1,-1,-1):
            if s[i]==x:k=i
            l[j][i]=k if k>=0 else f
    j+=1
c=0
i=0
j=0
while j<len(t):
    k=l[abc.index(t[j])][i]
    if k<i:c+=1
    i=k
    j+=1
print(c*len(s)+k+1)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations
import sys
import bisect
import string
sys.setrecursionlimit(10**6)
def SI():
    return input().split()
def MI():
    return map(int,input().split())
def I():
    return int(input())
def LI():
    return [int(i) for i in input().split()]
YN=['Yes','No']
mo=10**9+7

s=input()
t=input()
s=list(s)
t=list(t)
Ss=set(s)
St=set(t)
n=len(s)

alp=string.ascii_lowercase
di=dict([(i,j) for j,i in enumerate(alp)])
#print(di)
g=[{} for _ in range(n)]
fp=[10*10 for i in range(26)]
lp=[-1 for i in range(26)]

for i,c in enumerate(s):
    fp[di[c]]=min(i,fp[di[c]])
    for next_c in [di[l] for l in Ss]:
        if fp[next_c]!=-1:
            g[i][next_c]=(fp[next_c],1)

for i in range(n)[::-1]:
    lp[di[s[i]]]=i
    for next_c in [di[l] for l in Ss]:
        if lp[next_c]!=-1:
            g[i][next_c]=(lp[next_c],1 if i==lp[next_c] else 0)

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


#print(Ss,St,St-Ss)
if len(St-Ss)!=0:
    ans=-1
else:
    loop=0
    has=0
    st=di[t[0]]
    loop+=g[0][st][1]
    i_n=g[0][st][0]
    has=i_n
    for i in range(1,len(t)):
        ch=di[t[i]]
        loop+=g[i_n][ch][1]
        i_n=g[i_n][ch][0]
        has=g[i_n][ch][0]
        #print(loop,has,i_n,g[i_n][ch])
    ans=loop*n+has+1
print(ans)#,loop,has)
#print([[i,di[i]] for i in s])
'''
for i in g:
    print(sorted(list(i.items()),key=lambda x:x[0]))
'''

Submission status: Wrong Answer

Solution code:
from bisect import bisect

s = input()
t = input()

if len(set(t) & set(s)) != len(set(t)):
    print(-1)
    exit()

d = dict()

def judge(a,b):
    for ai in d[a]:
        if bisect(d[b],ai) != len(d[b]):
            return False
    return True

for i, si in enumerate(s):
    if si in d:
        d[si].append(i)
    else:
        d[si] = [i]

ans = 0

for i in range(len(t)-1):
    if judge(t[i],t[i+1]):
        ans += len(s)

ans += min(d[t[-1]]) + 1

print(ans)

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque
from collections import defaultdict
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

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 I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    s = S()
    t = S()
    ans = 0
    s_dict = defaultdict(list)
    for ix, c in enumerate(s):
        s_dict[c].append(ix)
    cur_ix = 0
    for counter, c in enumerate(t):
        if s_dict.get(c) == None:
            print(-1)
            return
        char_ix_list = s_dict.get(c)
        # cur_ixより大きい値を見つける
        pos = bisect.bisect_right(char_ix_list, cur_ix)
        # cur_ixより大きい値がないとき、リセット
        if pos >= len(char_ix_list):
            ans += len(s)
            cur_ix = char_ix_list[0]
        # cur_ixより大きい値が見つかった時、cur_ixを更新
        else:
            cur_ix = s_dict.get(c)[pos]
        # if last, add cur_ix to answer
        if counter == len(t)-1:
            ans += (cur_ix + 1)
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from re import finditer
from bisect import bisect_left

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


    str_dict = defaultdict(list)



    for char in set(t):
        c_iter = finditer(char, s)
        flag = True
        for j in c_iter:
            flag = False
            str_dict[char] += [j.start() + 1]
        if flag:
            return '-1'


    ans = 0
    for i in t:
        remain = ans % len(s)
        array = str_dict[i]
        str_ind = bisect_left(array, remain)
        if str_ind != len(array):
            ans += array[str_ind] - remain
        else:
            ans += len(s) - remain + array[0]
    return ans


print(main())

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
s = input()
t = input()

ds = defaultdict(int)
for i in range(len(s)):
    ds[s[i]] += 1
dt = defaultdict(int)
for i in range(len(t)):
    dt[t[i]] += 1

possible = True
for ti in dt:
    if ti not in ds:
        possible = False
        break


if possible:
    n = len(s)
    pos = defaultdict(list)
    for i in range(n*2):
        pos[s[i%n]].append(i)

    edge = defaultdict(list)
    for c in pos:
        x = 0
        for i in range(n):
            if i >= pos[c][x]:
                x += 1
            edge[c].append(pos[c][x])

    ans = 0
    x = 0
    for i in range(n):
        if s[i] == t[0]:
            ans = i + 1
            x = i
            break

    for i in range(1, len(t)):
        ans += (n + edge[t[i]][x%n] - x) % n
        x = edge[t[i]][x%n]

else:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
import bisect
import sys
s=input()
t=input()

d=defaultdict(list)

ls=len(s)
lt=len(t)

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

buf=-1
l=0
for i in range(lt):
    if not d[t[i]]:
        print(-1)
        sys.exit()
    idx=bisect.bisect_left(d[t[i]],buf)
    if idx>=len(d[t[i]]):
        buf=d[t[i]][0]
        l+=1
    else:
        buf=d[t[i]][idx]
print(l*ls+buf+1)