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.

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')


def A():
    d = {"Sunny":1 , "Cloudy":2, "Rainy":0}
    a = ["Sunny", "Cloudy", "Rainy"]
    print(a[d[input().rstrip()]])
    return


def B():
    s = S()
    for i, si in enumerate(s):
        if i % 2:
            if si == "R":
                print("No")
                return
        else:
            if si == "L":
                print("No")
                return
    print("Yes")
    return


def C():
    n, k, q = LI()
    d = [0] * n
    for _ in range(q):
        a = II() - 1
        d[a] += 1
    for a in d:
        if k - (q - a) > 0:
            print("Yes")
        else:
            print("No")
    return


def D():
    n,m = LI()
    a = LI()
    q = []
    for ai in a:
        heappush(q, -ai)
    for _ in range(m):
        heappush(q, heappop(q) / 2)
    ans = 0
    while q:
        ans += int(-heappop(q))
    print(ans)
    return


def E():
    s = S()
    t = S()
    d = defaultdict(list)
    for i,si in enumerate(s):
        d[si].append(i)
    if d[t[0]] == []:
        print(-1)
        return
    before = d[t[0]][0]
    ans = 0
    for ti in t[1:]:
        if d[ti] == []:
            print(-1)
            return
        a = d[ti]
        index = bisect_right(a, before)
        if index == len(a):
            ans += 1
            before = a[0]
        else:
            before = a[index]
    print(ans * len(s) + before + 1)
    return


def F():
    return


if __name__ == '__main__':
    E()

Solution (Python):
from bisect import bisect as bi
s = input()
t = input()
x,c,ans,num = [[] for i in range(26)],[0]*26,0,-1
for i in range(len(s)):
    x[ord(s[i])-97].append(i)
    c[ord(s[i])-97]+=1
for i in t:
    if x[ord(i)-97]:
        b = bi(x[ord(i)-97],num)
        if b==c[ord(i)-97]:
            ans+=len(s)
            num = x[ord(i)-97][0]
        else: num = x[ord(i)-97][b]
    else:
        ans,num = -1,-1
        break
print(ans+num+1)

Solution (Python):
import bisect
s = input()
t = input()



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

bi_left = bisect.bisect_left
bi_right = bisect.bisect_right
now = -1
ans = 0
for i, t in enumerate(t):
    ascii = ord(t) - 97
    if len(ch[ascii]) == 0:
        print("-1")
        exit()
    check = bi_right(ch[ascii], now)

    if check == len(ch[ascii]):
        now = ch[ascii][0]
        ans += 1
    else:
        now = ch[ascii][check]

print(ans*len(s)+now+1)

Solution (Python):
from sys import exit
s = input()
t = input()
tset = set(t)
slen = len(s)
aord = ord('a')
if len(tset - set(s)) != 0:
    print(-1)
    exit()
s2t = [i - aord for i in (s + s).encode('ascii')]
lut = [[-1] * slen for _ in range(26)]
for c in tset:
    b = ord(c) - aord
    j = 0
    for i in range(slen * 2 - 1, -1, -1):
        if s2t[i] == b:
            j = 0
        else:
            j += 1
        if i < slen:
            lut[b][i] = j
p = 0
for c in t:
    b = ord(c) - aord
    p += lut[b][p % slen] + 1
print(p)

Solution (Python):
from sys import exit
s = input()
t = input()
tset = set(t)
slen = len(s)
aord = ord('a')
if len(tset - set(s)) != 0:
    print(-1)
    exit()
s2t = [i - aord for i in (s + s).encode('ascii')]
lut = [[-1 for _ in range(slen)] for _ in range(26)]
for c in tset:
    b = ord(c) - aord
    j = 0
    for i in range(slen * 2 - 1, -1, -1):
        if s2t[i] == b:
            j = 0
        else:
            j += 1
        if i < slen:
            lut[b][i] = j
p = 0
for c in t:
    b = ord(c) - aord
    p += lut[b][p % slen] + 1
print(p)

Solution (Python):
def main():
    from sys import exit
    from builtins import ord, range
    s = input()
    t = input()
    tset = set(t)
    slen = len(s)
    aord = ord('a')
    if len(tset - set(s)) != 0:
        print(-1)
        exit()
    s2t = [i - aord for i in (s + s).encode('ascii')]
    lut = [[-1 for _ in range(slen)] for _ in range(26)]
    for c in tset:
        b = ord(c) - aord
        j = 0
        for i in range(slen * 2 - 1, -1, -1):
            if s2t[i] == b:
                j = 0
            else:
                j += 1
            if i < slen:
                lut[b][i] = j
    p = 0
    for c in t:
        b = ord(c) - aord
        p += lut[b][p % slen] + 1
    print(p)


main()

Solution (Python):
from bisect import bisect_left as bl
from bisect import insort_right as ir
from collections import defaultdict

s = input()
t = input()
len_s = len(s)

index = defaultdict(list)
for i, c in enumerate(s):
    ir(index[c], i)

ans = 0
now = 0
for c in t:
    if not index[c]:
        print('-1')
        break
    idx = bl(index[c], now)
    if idx == len(index[c]):
        ans += len_s
        now = index[c][0] + 1
    else:
        now = index[c][idx] + 1
else:
    print(ans + now)

Solution (Python):
from bisect import bisect_left

s = input()
t = input()

n = len(s)

c = [[] for _ in range(26)]

for i, x in enumerate(s + s):
    c[ord(x) - ord('a')].append(i)

ans = 0
p = -1
for x in t:
    d = ord(x) - ord('a')
    if len(c[d]) == 0:
        print(-1)
        exit()
    p = c[d][bisect_left(c[d], p+1)]
    if p >= n:
        p -= n
        ans += 1

print(ans * n + p + 1)

Solution (Python):
from collections import defaultdict
from bisect import bisect_right
s = input()
t = input()
ss = set(s)
tt = set(t)
count = 0
for i in tt:
  if not i in ss:
    print(-1)
    break
else:
  dic = defaultdict(list)
  for i in range(len(s)):
    dic[s[i]] += [i+1]
  ans = 0
  for i in range(len(t)):
    x = ans%len(s)
    if dic[t[i]][-1]<=x:
      ans = ans - x + len(s) + dic[t[i]][0]
    else:
      ind = bisect_right(dic[t[i]], x)
      ans = ans - x + dic[t[i]][ind]
  print(ans)

Solution (Python):
from collections import defaultdict
from bisect import bisect_right
s = input()
t = input()
ss = set(s)
tt = set(t)
count = 0
for i in tt:
  if not i in ss:
    print(-1)
    break
else:
  dic = defaultdict(list)
  for i in range(len(s)):
    dic[s[i]] += [i+1]
  ans = 0
  for i in range(len(t)):
    x = ans%len(s)
    if dic[t[i]][-1]<=x:
      ans = ans - x + len(s) + dic[t[i]][0]
    else:
      ind = bisect_right(dic[t[i]], x)
      ans = ans - x + dic[t[i]][ind]
  print(ans)

Solution (Python):
import sys
import collections
import bisect
s = raw_input()
t = raw_input()
p, e, n = 0, 1, len(s)
ss = set(s)
idx = collections.defaultdict(list)
for i in xrange(n):
    idx[s[i]].append(i)

for tt in t:
    q = p % n
    if not tt in idx:
        e = 0
        break
    indexs = idx[tt]
    
    res = bisect.bisect_left(indexs, q)
    p += indexs[res] - q + 1 if res < len(indexs) else -q + n + indexs[0] + 1
print((p+1)*e-1)

Solution (Python):
def slove():
    import sys
    import collections
    import bisect
    input = sys.stdin.readline
    s = str(input().rstrip('\n'))
    t = str(input().rstrip('\n'))
    d = collections.defaultdict(list)
    for i in range(len(s)):
        d[s[i]] += [i]
    loop = 0
    cur = 0
    for i in range(len(t)):
        p = bisect.bisect_left(d[t[i]], cur)
        if p == 0 and len(d[t[i]]) == 0:
            print(-1)
            exit()
        elif p == len(d[t[i]]):
            loop += 1
            cur = d[t[i]][0] + 1
        else:
            cur = d[t[i]][p] + 1
    print(len(s) * loop + cur)


if __name__ == '__main__':
    slove()

Solution (Python):
import bisect
s = input()
len_s = len(s)
t = input()

ind_dict = {i : [] for i in t}
for i, _s in enumerate(s):
    if _s in t:
        ind_dict[_s] += [i]

def get_least(last, s, dic):
    ls = dic[s]
    ind = bisect.bisect_right(ls, last)
    if ind >= len(ls):
        return ls[0]
    else:
        return ls[ind]

if -1 in [s.find(_t) for _t in t]:
    print(-1)
else:
    cnt = 0
    last = get_least(-1, t[0], ind_dict)
    _next = last
    for _t in t[1:]:
        _next = get_least(last, _t, ind_dict)
        if _next <= last:
            cnt += 1
        last = _next
    print(cnt * len(s) + _next + 1)

Solution (Python):
from bisect import bisect

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

idxs_S = [[] for _ in range(26)] 
for i, c in enumerate(S):
    idx = ord(c) - ord("a")
    idxs_S[idx].append(i)


for c in set(T):
    if len(idxs_S[ord(c) - ord("a")]) == 0:
        print(-1)
        exit()

cnt_all_S = 0
idx_c = -1
for c in T:
    tmp = ord(c) - ord("a")
    idx = bisect(idxs_S[tmp], idx_c)
    if idx == len(idxs_S[tmp]): 
        idx_c = idxs_S[tmp][0] 
        cnt_all_S += 1
    else:
        idx_c = idxs_S[tmp][idx]

print(N*cnt_all_S + idx_c + 1)

Solution (Python):
slist = input()
tlist = input()
scounter = 0
slength=len(slist)
slist=slist+slist
preposition=-1
for tchar in tlist:
    preposition=slist.find(tchar, preposition+1)
    if preposition==-1:
        scounter=-1
        break
    elif preposition>=slength:
        scounter+=slength
        preposition-=slength
    
if (scounter==-1):
    print(scounter)
else:
    print(scounter+preposition+1)

Solution (Python):
import sys

s = input()
t = input()
s_len = len(s)
t_len = len(t)
index_list = [0]*t_len
rt1 = 0
rt2 = 0
s = s + s
for m in range(t_len):
	rt1 = s.find(t[m],rt1)
	if rt1 == -1:
		print(rt1)
		sys.exit()
	else:
		
		
		if rt1 < s_len:
			pass
		else:
			rt1 = rt1 % s_len
			rt2 += 1
	rt1 += 1
rt = rt1 + rt2 * s_len
print(rt)

Solution (Python):
s=input()
t=input()
ans1=0
ans2=0
m=len(s)
n=len(t)
s=s+s
for i in range(n):
  a=s.find(t[i],ans2)
  if a==-1:
    print(-1)
    exit()
  if a>=m:
    ans1+=1
  ans2=a%m+1
print((ans1*m)+ans2)

Solution (Python):
alpha = list("abcdefghijklmnopqrstuvwxyz")

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

info = [[0] * len(s) for _ in range(26)]

ss = s[:] * 2

for i in range(26):
    last = -1
    for j in range(len(ss)-1,-1,-1):
        info[i][j%(len(s))] = last
        if ss[j] ==  alpha[i]:
            last = j % (len(s))


count = 0
num = 0
place = -1

while num < len(t):
    x = info[alpha.index(t[num])][place]
    if x > place:
        count += x - place
    else:
        count += x - place + len(s)
    place = x
    num += 1

s_ = [0] * 26
t_ = [0] * 26
for lets in s:
    s_[alpha.index(lets)] = 1
for lett in t:
    t_[alpha.index(lett)] = 1
for i in range(26):
    if s_[i] < t_[i]:
        count = -1
        break

print(count)

Solution (Python):
import sys
import bisect

s = input()
t = input()

dic = {}

for i, c in enumerate(s):
    if c not in dic:
        dic[c] = []
        
    dic[c].append(i)

currentIndex = -1
roop = 0

for c in t:
    if c not in dic:
        print(-1)
        sys.exit()
    
    if currentIndex >= dic[c][-1]:
        roop += 1
        currentIndex = dic[c][0]
    else:
        index =  bisect.bisect_right(dic[c], currentIndex)
        currentIndex = dic[c][index]

result = (roop * len(s)) + currentIndex + 1
print(result)

Solution (Python):
from collections import defaultdict
import bisect
s = input()
t = input()
ls = len(s)
dbls = s*2
idx = 0
ans = 0
dic = defaultdict(list)

for i, c in enumerate(dbls):
    dic[c] += [i+1]

for c in t:
    if not c in dic.keys():
        print(-1)
        exit()
    lst = dic[c]
    i = bisect.bisect_right(lst, idx)
    idx = lst[i]
    if idx > ls:
        ans += ls
        idx -= ls
    else:
        idx = lst[i]

if not idx == 0:
    ans += idx
print(ans)

Solution (Python):
S=input();T=input();p=0;e=1
for s in T:
  q=p%len(S)
  if not s in S:e=0;break
  if s in S[q:]:p+=S[q:].index(s)+1
  else:p+=S.index(s)+len(S[q:])+1
print((p+1)*e-1)

Solution (Python):
s = str(input().strip())
t = str(input().strip())

pos = [[] for _ in range(30)]

for i, v in enumerate(s):
    pos[ord(v) - ord('a')].append(i + 1)

pre = 0
ans = 0
from bisect import bisect_right

for i in t:
    g = ord(i) - ord('a')
    p = bisect_right(pos[g], pre)
    if p >= len(pos[g]):
        if len(pos[g]):
            ans += len(s)
            pre = pos[g][0]
            continue
        else:
            print(-1)
            exit(0)
    pre = pos[g][p]

ans += pre
print(ans)

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

s_ = s[:]

ti = 0
ans = 0
flag = True

while ti < len(t):
    si = s_.find(t[ti])
    
    if si != -1:
        ans += si + 1
        s_ = s_[si+1:]
        ti += 1
        flag = False
    else:
        if flag:
            print(-1)
            exit(0)
        ans += len(s_)
        s_ = s[:]
        flag = True
        
print(ans)

Solution (Python):
from collections import defaultdict

import bisect 


s = input()
t = input()
l = len(s)

idx_dict = defaultdict(list)


for i, v in enumerate(s):
    idx_dict[v].append(i)





l = len(s)
rnd = 0
idx = 0
ans = 0
p_v = ''


for v in t:
    
    if v not in idx_dict:
        ans = -1
        break
    
    if v == p_v:
        idx += 1
    arr = idx_dict[v]
    i = bisect.bisect_left(arr, idx)
    try:
        idx = arr[i]
    except IndexError:
        idx = arr[0]
        rnd += 1
    p_v = v

if not ans:
        ans = ((rnd * l) + idx) + 1
        
print(ans)

Solution (Python):
import bisect
S = input()
T = input()
D = [[] for _ in range(26)]
for i in range(26):
  D[i] = [0] * S.count(chr(97 + i))
P = [0] * 26
for i, s in enumerate(S):
  n = ord(s) - 97
  D[n][P[n]] = i + 1
  P[n] += 1
pos = 0
loop = 0
for t in T:
  n = ord(t) - 97
  if D[n] == []:
    print(-1)
    break
  _d = bisect.bisect(D[n], pos)
  _pos = D[n][_d % len(D[n])]
  if _pos <= pos:
    loop += 1
  pos = _pos
else:
  print(len(S) * loop + pos)

Solution (Python):
def main():
  s = list(map(lambda x:ord(x)-97, list(input())))
  ls = len(s)
  ss = set(s)
  t = list(map(lambda x:ord(x)-97, list(input())))
  lt = len(t)
  st = set(t)
  td = [list() for _ in range(26)]
  if not st.issubset(ss):
    print(-1)
    exit()
  for i in range(lt-1):
    td[t[i]].append(t[i+1])
  md = [None for _ in range(ls)]
  cd = [0]*26
  for i in range(ls-1,-1,-1):
    cd[s[i]] = i + ls
  for i in range(ls-1,-1,-1):
    md[i] = cd.copy()
    cd[s[i]] = i
  ans = 0
  cur = cd[t[0]]
  for i in range(lt-1):
    cur = md[cur][t[i+1]]
    ans += (cur//ls)
    cur %= ls
  print(1 + ans*ls+cur)

if __name__ == "__main__":
  main()

Solution (Python):
import bisect

s = input()
t = input()
lis = [[]for _ in range(26)]

for i,j in enumerate(s):
    j = ord(j) -ord("a")
    lis[j].append(i)

lenlis = [len(lis[i]) for i in range(26)]

now = 0
ans = 0
for i in t:
    i = ord(i) -ord("a")
    if lenlis[i] == 0:
        ans = -1
        break
    insert_index = bisect.bisect_left(lis[i],now)
    if insert_index == lenlis[i]:
        ans += 1
        now = lis[i][0] +1
    else:
        now = lis[i][insert_index] + 1

if ans == -1:
    print(-1)
else:
    ans = ans*len(s) + now
    print(ans)

Solution (Python):
from bisect import*
s=input()
t=input()
d={}
for i,c in enumerate(s):
    d.setdefault(c,[]).append(i+1)
m=-1
n=len(s)
r=0
for c in t:
    if not c in d:
        print(-1)
        exit()
    i=bisect(d[c],m)
    if len(d[c])==i:
        r+=1
        m=d[c][0]
    else:
        m=d[c][i]
print(r*n+m)

Solution (Python):
from sys import exit, stderr, stdin, setrecursionlimit
input = stdin.readline


def debug(var, name="hoge"):
    print(name +":" + str(type(var)) + " = " + repr(var), file=stderr)
    return



def main():
    
    S = str(input().rstrip())*2
    T = str(input().rstrip())
    LS = len(S)//2
    LT = len(T)
    S *= 3
    
    char_p = dict()
    for i in range(LS):
        if not S[i] in char_p:
            char_p[S[i]] = i

    
    char_d = dict(zip(char_p.keys(),[[0 for __ in range(LS+char_p[c])] for c in char_p]))
    for c in char_p:
        dis = 1
        for i in range(LS+char_p[c]-1,-1,-1):
            if S[i] == c:
                char_d[c][i] = dis
                dis = 1
            else:
                char_d[c][i] = dis
                dis += 1
    
    debug(char_d)
    init = True
    for t in T:
        if t not in char_p:
            print(-1)
            exit()
        else:
            debug(t,'string')
            if init:
                cur = char_p[t]
                init = False
            
            else:
                rel_cur = cur%LS
                debug(rel_cur,"relative_cursol")
                cur += char_d[t][rel_cur]
        debug(cur,"cur")
        
    print(cur+1)






if __name__ == "__main__":
    main()

Solution (Python):
def get_answer(input_list):
    so = input_list[0]
    t = input_list[1]

    s_len = len(so)

    t_i = [-1] * len(t)
    s = so + so
    s_index = 0
    for i in range(len(t)):
        index = s.find(t[i], s_index)
        if index < 0:
            break
        index = index % s_len
        t_i[i] = index
        s_index = index + 1
        s_index = s_index % s_len

    if -1 in t_i:
        return -1

    t_len = len(t_i)
    ret = 0
    ret_i = 0
    for i in range(t_len):
        t1 = t_i[i]
        ret = t1
        if i < t_len - 1:
            t2 = t_i[i + 1]
            if t1 >= t2:
                ret_i += 1

    return ret_i * s_len + ret + 1


if __name__ == "__main__":
    input_list = []
    while True:
        try:
            input1 = input()
            if not input1:
                break
            if len(input1) == 0:
                break
            input_list.append(input1)
        except EOFError:
            break
    print(get_answer(input_list))

Solution (Python):
def get_answer(input_list):
    so = input_list[0]
    t = input_list[1]

    s_len = len(so)

    """
    contest son
    s:5
    o:1 7+2
    n:2 7+3
    
    aabbcc abca
    a:0 0
    b:2 2
    c:4 4
    a:0 0 +6
    
    aa aaaa
    a:0
    a:1
    a:0 + 2
    a:1 + 2   
    
    aabbcc abccba
    a 0
    b 2
    c 4
    c 5
    b 2 6
    a 0 12 = 13
    """

    t_i = [-1] * len(t)
    s = so + so
    s_index = 0
    for i in range(len(t)):
        index = s.find(t[i], s_index)
        if index < 0:
            break
        index = index % s_len
        t_i[i] = index
        s_index = index + 1
        s_index = s_index % s_len

    if -1 in t_i:
        return -1


    t_len = len(t_i)
    ret = 0 
    ret_i = 0
    for i in range(t_len):
        t1 = t_i[i]
        ret = t1
        if i < t_len - 1:
            t2 = t_i[i + 1]
            if t1 >= t2:
                ret_i += 1


    """
    for i in range((1000 - s_index) * s_len):
        find_flag = True
        ss = s
        for tt in t:
            ii = ss.find(tt)
            if ii < 0:
                find_flag = False
                break
            ss = ss[ii + 1:]
        if find_flag:
            ret = len(s)
            break
        s += so[s_index]
        s_index = (s_index + 1) % s_len
    """
    return ret_i * s_len + ret + 1


if __name__ == "__main__":
    input_list = []
    while True:
        try:
            input1 = input()
            if not input1:
                break
            if len(input1) == 0:
                break
            input_list.append(input1)
        except EOFError:
            break
    print(get_answer(input_list))

Solution (Python):
import bisect
import sys
S = input()
T = input()



s_index = {}
for i in range(len(S)):
    if S[i] in s_index:
        s_index[S[i]].append(i + 1)
    else:
        s_index[S[i]] = [i+1]


current_s_index = 0
loop_count = 0
ans = 0
for t in T:
    if not t in s_index:
        print(-1)
        sys.exit()

    if current_s_index >= s_index[t][-1]:
        current_s_index = s_index[t][0]
        loop_count += 1
    else:
        index = bisect.bisect(s_index[t], current_s_index)
        current_s_index = s_index[t][index]

print(current_s_index + loop_count * len(S))

Solution (Python):
import sys
import numpy as np
import bisect
s = input()
t = input()



count = 0
s_len = len(s)
s_list = np.zeros(len(s))
t_list = []*len(t)
indexes = []

for i in range(26):
  
  indexes.append([j for j, x in enumerate(s) if x == chr(i + ord('a')) ])
  


for i,k in enumerate(t):

  index = indexes[ord(k)-ord('a')]
  
  if len(index) == 0:
    print(-1)
    sys.exit(0)
  else:
    t_list.insert(i,index)
    


pre = -1
for i in range(len(t)):
  
  
  high = bisect.bisect_left(t_list[i], pre+1) 

  if high >= len(t_list[i]):
    
    count += s_len - pre  + t_list[i][0]
    pre = t_list[i][0] 
  else:
    
    count += t_list[i][high] - pre 
    pre = t_list[i][high]

print(count)

Solution (Python):
import sys
input = sys.stdin.readline

import bisect

s = input().split() 
s = list(s[0])
t = input().split() 
t = list(t[0])
f = [[] for _ in range(26)]

for i in range(len(s)):
    f[ord(s[i])-97].append(i)

g = [-1 for _ in range(len(t))]
if len(f[ord(t[0])-97]) == 0:
    print(-1)
    sys.exit()
g[0] = f[ord(t[0])-97][0]
cnt = 0
for i in range(1,len(t)):
    if len(f[ord(t[i])-97]) == 0:
        print(-1)
        sys.exit()

    if f[ord(t[i])-97][-1] > g[i-1]:
        index = bisect.bisect_right(f[ord(t[i])-97], g[i-1])
        g[i] = f[ord(t[i])-97][index]
    else:
        g[i] = f[ord(t[i])-97][0]
    if g[i] <= g[i-1]:
        cnt += 1

print(cnt*len(s)+g[-1]+1)

Solution (Python):
import bisect
s = input()
t = input()
moji = {}
for i in range(len(s)):
    if s[i] in moji.keys():
        moji[s[i]].append(i)
    else:
        moji[s[i]] = [i]

now = -1
kaisu = 0
flag = True
for i in range(len(t)):
    if t[i] in moji.keys():
        basho = moji[t[i]]
        lenbasho = len(basho)
        nowindex = bisect.bisect_right(basho, now)
        if nowindex == lenbasho:
            now = basho[0]
            kaisu += 1
        else:
            now = basho[nowindex]
    else:
        flag = False
        break
if flag:
    ans = kaisu * len(s) + now + 1
    print(ans)
else:
    print(-1)

Solution (Python):
s = input()
t = input()
cnt = 0
last = 0
b = [{} for i in range(len(s))]
b[-1][s[-1]] = len(s) - 1
for i in range(len(s)-1)[::-1]:
    b[i] = b[i + 1].copy()
    b[i][s[i]] = i
if t[0] in b[0]:
    last = b[0][t[0]]
else:
    print(-1)
    exit()
for i in t[1:]:
    if last < len(s) - 1 and i in b[last + 1]:
        last = b[last + 1][i]
    else:
        if i not in s:
            print(-1)
            exit()
        last = b[0][i]
        cnt +=1
print(cnt*len(s) + last + 1)

Solution (Python):
import sys
sys.setrecursionlimit(int(1e6))

s = input()
t = input()

len_s = len(s)
set_s = set(s)
set_t = set(t)

if len(set_t - set_s) != 0:
    print(-1)
    sys.exit()

ss = s + s
indexes_c = {}
for c in set_t:
    indexes = list()
    index = 0
    index_sum = 0
    word = ss
    while index_sum < len_s:
        index = word.index(c)+1
        index_sum += index
        indexes.append(index_sum)
        word = word[index:]
    indexes_c[c] = indexes

from bisect import bisect_right
ans = 0
for c in t:
    i = ans % len_s
    indexes = indexes_c[c]
    ans += indexes[bisect_right(indexes, i)] - i

print(ans)

Solution (Python):
import sys
s = input()
t = input()
table = [[len(s) for i in range(len(s))] for j in range(26)]
sset = set(s)
tset = set(t)
for i in range(len(s)):
  table[ord(s[i])-97][i] = 0
for letter in sset:
  i = ord(letter) - 97
  for j in range(len(s)):
    table[i][len(s)-j-2] = min(table[i][len(s)-j-1] +1, table[i][len(s)-j-2])
  for j in range(len(s)):
    if table[i][len(s)-j-2] < len(s): break
    table[i][len(s)-j-2] = min(table[i][len(s)-j-1] +1, table[i][len(s)-j-2])

if tset - sset:
  print(-1)
  sys.exit()
    
place = 0
ans = 0
for i in range(len(t)):
  letter = t[i]
  move = table[ord(t[i])-97][place]
  ans += move + 1
  place = (place + move+1)%len(s)
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(int(1e6))

s = input()
t = input()

len_s = len(s)
set_s = set(s)
set_t = set(t)

if len(set_t - set_s) != 0:
    print(-1)
    sys.exit()

n = {}
ss = s + s
ans = 0
for c in t:
    i = ans % len_s
    if not c in n:
        n[c] = [0] * len_s
    if n[c][i] == 0:
        n[c][i] = ss[i:].find(c) + 1
    ans += n[c][i]

print(ans)

Solution (Python):
import sys
from bisect import bisect_right

s = input()
t = input()

t_set = set(t)

if len(t_set -set(s)) != 0:
    print(-1)
    sys.exit()

s_len = len(s)
def index_list(char):
    word = s
    ret = list()
    sum = 0
    try:
        while True:
            index = word.index(char)+ 1        
            sum+=index
            ret.append(sum)
            word = word[index:]
    except:
        if sum == 0:
            ret.append(-1)
    return ret

alpha_dict = dict()
for char in t_set:
    alpha_dict[char] = index_list(char)

index_old = 0
n_s = 0
for char in t:
    index = alpha_dict[char]
    
    flg = True
    
    if index[-1] <= index_old:
        pass
    else:
        index_old = index[bisect_right(index, index_old)]
        flg =False
    if flg:
        index_old = index[0]
        n_s += 1
        
print(n_s*s_len + index_old)

Solution (Python):
import sys
s = input()
t = input()
tset = set(t)
slen = len(s)
if len(tset - set(s)) != 0:
    print(-1)
    sys.exit()
s2t = [i - ord('a') for i in (s + s).encode('ascii')]
lut = [[-1 for _ in range(slen)] for _ in range(26)]
for c in tset:
  b = ord(c) - ord('a')
  j = 0
  for i in range(slen * 2 - 1, -1, -1):
    if s2t[i] == b:
      j = 0
    else:
      j += 1
    if i < slen:
      lut[b][i] = j
p = 0
for c in t:
  b = ord(c) - ord('a')
  p += lut[b][p % slen] + 1
print(p)

Solution (Python):
S = input()
T = input()


def solve(S, T):
    for t in set(T):
        if t not in set(S):
            return -1

    S_double = S+S
    len_s = len(S)
    ans = -1
    for t in T:
        ans += S_double[(ans+1) % len_s:].index(t) + 1
    return ans + 1


print(solve(S, T))

Solution (Python):
from bisect import bisect_left
 
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
 
 
def main(s, t):
    positions = {char: [] for char in ALPHABET}
    for i, char in enumerate(s):
        positions[char].append(i)
 
    current = 0
    answer = 0
    for char in t:
        pos_num = len(positions[char])
        if pos_num < 1:
            return -1
        idx = bisect_left(positions[char], current)
        if idx < pos_num:
            current = positions[char][idx] + 1
        else:
            answer += len(s)
            idx = bisect_left(positions[char], 0)
            current = positions[char][idx] + 1
 
    answer += current
    return answer
 
 
s = input()
t = input()
print(main(s, t))

Solution (Python):
S, T = input(), input()

def func(S, T):

    merge_S = list(set(S))
    merge_T = list(set(T))
    for t in merge_T:
        if t not in merge_S:
            return -1

    S_2 = S+S
    len_s = len(S)

    ans = -1

    for t in T:
        ans += S_2[(ans+1)%len_s:].index(t) + 1

    return ans + 1

print(func(S,T))

Solution (Python):
s = input()
t = input()
ls = len(s)
lt = len(t)


ss = []
ss1 = [[] for _ in range(26)]
ss2 = [[] for _ in range(26)]
for i in range(ls):
  ss1[ord(s[i]) - 97].append(i)
  ss2[ord(s[i]) - 97].append(i+ls)
for k in range(26):
  ss.append(ss1[k] + ss2[k])
ans = 0
mans = 0
import bisect
for j in range(lt):
  now = ord(t[j]) - 97
  if ss[now] == []:
    print(-1)
    break
  here = bisect.bisect_left(ss[now],mans)
  ans += ss[now][here] - mans + 1
  mans = ans % ls
else:
  print(ans)

Solution (Python):

import math
import bisect
from collections import defaultdict

S = list(str(input()))
T = list(str(input()))

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

flag = 0
x = -1
loop = 0
for t in T:
    tindl = index[t]
    if len(tindl) == 0:
        print(-1)
        flag = 1
        break
    j = bisect.bisect(tindl,x)
    if j == len(tindl):
        loop+=1
        x = tindl[0]
    else:
        x = tindl[j]


if flag == 0:
    print(loop*len(S)+x+1)

Solution (Python):
S = input()
T = input()
pos = 0

for s in T:
  if not s in S:
    pos = -1
    break
  if s in S[pos%len(S):]:
    pos += S[pos%len(S):].index(s)+1
  else:
    pos += S.index(s)+len(S[pos%len(S):])+1
print(pos)

Solution (Python):
def main():
    s = input()
    t = input()
    s2 = s * 2
    sett = list(set((t)))
    settindex = {}
    for i in sett:
        settindex[i] = sett.index(i)
        if i not in s:
            print(-1)
            return
    lens = len(s)
    
    index = [[-1] * len(sett) for _ in range(lens)]
    ans = 0
    n = 0
    for i in t:
        j = settindex[i]
        if index[n][j] == -1:
            index[n][j] = s2[n:].index(i)
        ans += index[n][j] + 1
        n += index[n][j] + 1
        n %= lens
    print(ans)


if __name__ == '__main__':
    main()