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-----
contest
son

-----Sample Output-----
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.

Difficulty: interview

Starter code:

Solutions:
import sys
import math
import bisect
import heapq
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

# coding: utf-8
# hello worldと表示する
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return list(map(int, input().split()))
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
#def MXI(): return [LI() for i in range(n)]　
def SI(): return input().rstrip()
def printns(x): print(('\n'.join(x)))
def printni(x): print(('\n'.join(list(map(str,x)))))
inf = 10**17
mod = 10**9 + 7
s=SI()
t=SI()
a=len(s)
b=len(t)
#アルファベットから数字へと変換する辞書
alphasm=[chr(i) for i in range(97, 97+26)]
alphadic={}
for i in range(26):
    alphadic[alphasm[i]]=i
strlis=[[] for i in range(26)]
#print(alphadic)
#print(strlis)
for i in range(a):
    strlis[alphadic[s[i]]].append(i)
#print(strlis)
rd=0
pos=-1
#print(strlis[a])
i=0
while i<b:
    if len(strlis[alphadic[t[i]]])==0:
        print((-1))
        return
        #print("a")
    if pos==-1:
        pos=strlis[alphadic[t[i]]][0]
        i+=1
        #print("b")
    elif strlis[alphadic[t[i]]][-1]<=pos:
        rd+=1
        pos=-1
        #print("c")
    else:
        pos=strlis[alphadic[t[i]]][bisect_right(strlis[alphadic[t[i]]],pos)]
        i+=1
        #print("d")
    #print(rd,pos)
print((rd*a+pos+1))


    
        
#現在の周回数、何個目かの情報を持っておく
#次の周回に行くかどうかの判定 行かないなら二分探索




            
    


3
# -*- coding:utf-8 -*-

from collections import defaultdict
import bisect

def main():
  s = input().strip()
  t = input().strip()
  ns = len(s)
  
  if len(set(list(t)) - set(list(s))):
    print((-1))
    return
  
  ichs = defaultdict(list)  
  for i, c in enumerate(s):
    ichs[c].append(i)
    
  ic = -1
  cnt = 0
  for c in t:
    ix = bisect.bisect_right(ichs[c], ic)
    
    if ix >= len(ichs[c]):
      cnt += 1
      ix = 0
    else:
      if ic == ichs[c][ix]:
        if ix + 1 >= len(ichs[c]):
          cnt += 1
          ix = 0
        else:
          ix += 1
    ic = ichs[c][ix]
  print((cnt*ns + ic + 1))
    
      
    
  

def __starting_point():
  main()


__starting_point()

def solve():
    import bisect
    S = input()
    T = input()
    dic = {}
    length = {}

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

    for k, v in list(dic.items()):
        if k not in length:
            length[k] = 0
        length[k] = len(v)

    l, turn, prov = len(S), 0, 0

    for t in T:
        if t not in dic:
            print((-1))
            return
        x = bisect.bisect(dic[t], prov)
        if x < length[t]:
            prov = dic[t][x]
        else:
            turn += 1
            prov = dic[t][0]
    print((turn * l + prov))

solve()



def main():
  s = str(input())
  s_ = set(list(s))
  t =  str(input())
  t_ =  set(list(t))
  alphabet = "abcdefghijklmnopqrstuvwxyz"
  if t_ <= s_:
    length_s = len(s)
    
    res = [[length_s]*(26)  for _ in range(length_s+1)]
    for i in range(length_s-1, -1, -1):
      for j in range(26):
        if s[i] == alphabet[j]:
          res[i][j] = i+1
        else:
          res[i][j] = res[i+1][j]
    ans = 0
    now = 0
    for i in range(len(t)):
      for j in range(26):
        if t[i] == alphabet[j]:
          ans += res[now][j]-now
          now = res[now][j]
          if now == length_s:
            if t[i] == s[-1]:
              now = 0
            else:
              ans += res[0][j]
              now = res[0][j]
    print(ans)
  else:
    print(-1)
if  __name__  == "__main__":
  main()

S = input()
T = input()

n = len(S)

al = [chr(c) for c in range(ord("a"), ord("a")+26)]
x = {a: [] for a in al}

for i in range(len(S)):
    for a in al:
        if a == S[i]:
            x[a].append(i)

def is_ok(arg):
    # 条件を満たすかどうか？問題ごとに定義
    if x[t][arg]+c*n > i:
        return True
    return False


def meguru_bisect(ng, ok):
    '''
    初期値のng,okを受け取り,is_okを満たす最小(最大)のokを返す
    まずis_okを定義すべし
    ng ok は  とり得る最小の値-1 とり得る最大の値+1
    最大最小が逆の場合はよしなにひっくり返す
    '''
    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(mid):
            ok = mid
        else:
            ng = mid
    return ok

i = -1
c = 0
for t in T:
    if not x[t]:
        print(-1)
        break
    if x[t][-1]+c*n <= i:
        c += 1
    i = x[t][meguru_bisect(-1, len(x[t])-1)]+c*n

else:
    print(i+1)

from collections import defaultdict
from bisect import *

s,t = input(),input()
before,count = len(s),0
idx = defaultdict(list)

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

for i,l in enumerate(s):
  idx[l] += [i]
  
for c in t:
  N = idx[c]
  index = bisect_left(N, before)
  if index > len(N) - 1:
    before = N[0] + 1
    count += 1
  else:
    before = N[index] + 1
    
print((count - 1) * len(s) + before)

import bisect
s=input()
t=input()
dic={}
for i in range(len(t)):
  if t[i] in dic:
    continue
  if t[i] not in dic:
    dic[t[i]]=[]
for i in range(len(s)):
  if s[i] in dic:
    dic[s[i]].append(i)
for k,v in dic.items():
  if v==[]:
    print(-1)
    return
n=-1
k=0

for i in range(len(t)):
  l=bisect.bisect_right(dic[t[i]],n)
  if l<len(dic[t[i]]):
    n=dic[t[i]][l]
  else:
    n=dic[t[i]][0]
    k+=1
print(len(s)*k+n+1)

def f():
    s,t=input(),input()
    n,m=len(s),len(t)
    table=[[]for i in  range(26)]
    d={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

    for j in range(n):
        table[d[s[j]]].append(j)
    now=0
    ind=0
    if set(list(t))-set(list(s)):print(-1);return
    from bisect import bisect_left as bl
    for p in t:
        if ind>table[d[p]][-1]:now+=1;ind=0
        ind=table[d[p]][bl(table[d[p]],ind)]+1

    print(now*n+ind)
def __starting_point():
    f()
__starting_point()

import heapq

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

s=input()
t=input()
ds={}
for i in range(len(s)):
  if s[i] in ds:
    ds[s[i]].append(i+1)
  else:
    ds[s[i]]=[i+1]
n=len(s)
now=0 # mod n
ans=0
from bisect import bisect_right
for ti in t:
  if ti not in ds:
    print((-1))
    return
  tmp=bisect_right(ds[ti],now)
  if tmp==len(ds[ti]):
    get=n+ds[ti][0]
  else:
    get=ds[ti][tmp]
  ans+=get-now
  #print(now,get)
  now=(get)%n
print(ans)
#print(ds)


def main():
    from bisect import bisect_left

    S = input()
    T = input()

    L = len(S)

    pos = tuple(list() for _ in range(26))
    orda = ord('a')
    for i, c in enumerate(S):
        j = ord(c) - orda
        pos[j].append(i)

    rep = 0
    curr = 0
    for c in T:
        j = ord(c) - orda

        if not pos[j]:
            print((-1))
            return

        i = bisect_left(pos[j], curr)
        if i == len(pos[j]):
            rep += 1
            i = 0  # pos[j][0]文字目がc
        curr = pos[j][i] + 1  # pos[j][i]にしたら同じ文字が続くケースでWA

    print((rep * L + curr))


def __starting_point():
    main()

__starting_point()

from collections import defaultdict
from bisect import bisect_left


def solve(s, t):
    dd = defaultdict(list)
    for i, c in enumerate(s):
        dd[c].append(i)
    inv = 0
    index = 0
    for c in t:
        x = bisect_left(dd[c], index)
        if x == len(dd[c]):
            inv += 1
            if not dd[c]:
                return -1
            index = dd[c][0] + 1
        else:
            index = dd[c][x] + 1
    return len(s) * inv + index


def main():
    s = input()
    t = input()
    print((solve(s, t)))


def __starting_point():
    main()

__starting_point()

import bisect

s = input()
t = input()
n = len(s)
s0 = {}
for i in range(n):
    s0.setdefault(s[i], [])
    s0[s[i]].append(i)
num1 = 0
num2 = -1
flag = True
for i in t:
    if i not in s:
        flag = False
        break
    num = bisect.bisect_right(s0[i], num2)
    if num == len(s0[i]):
        num1 += 1
        num2 = s0[i][0]
    else:
        num2 = s0[i][num]
if flag == True:
    print(num1 * n + num2 + 1)
else:
    print(-1)

import sys
import math
import heapq
import bisect
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


# -------------------------------------------------------------
# main
# -------------------------------------------------------------
S = input().rstrip()
T = input().rstrip()

# set:T が set:S に含まれない => S にない文字を T で使っていたら
if not set(T) <= set(S):
    print((-1))
    return

ind = -1
cnt = 0
for t in T:
    # 現在の index 以降から探索する
    ind = S.find(t,ind+1)
    # 見つからない場合は先頭から探索し直し, loop countを+1
    if ind == -1:
        cnt += 1
        ind = S.find(t)

print((len(S) * cnt + ind + 1))


from bisect import bisect_left


S = input()
T = input()
if any(c not in S for c in T):
    print((-1))
    return

N = len(S)
pos = {c: [] for c in "abcdefghijklmnopqrstuvwxyz"}
for i in range(N):
    pos[S[i]].append(i)

loop = 0
cur = 0
for c in T:
    nxt = bisect_left(pos[c], cur)
    if nxt == len(pos[c]):
        loop += 1
        cur = pos[c][0] + 1
    else:
        cur = pos[c][nxt] + 1
print((loop * N + cur))


from bisect import bisect_right

s = input()
t = input()

n = len(s)

mp = [[] for _ in range(26)]
s += s
for i in range(len(s)):
    mp[ord(s[i]) - ord('a')].append(i)

ans = 0
now = -1
for i in range(len(t)):
    a = ord(t[i]) - ord('a')
    nxt = bisect_right(mp[a], now)
    if len(mp[a]) == nxt:
        print((-1))
        return

    ans += mp[a][nxt] - now
    now = mp[a][nxt]
    if now >= n:
        now -= n

print(ans)


from collections import defaultdict
from bisect import bisect

s = input()
S = len(s)
t = input()
T = len(t)
D = defaultdict(list)
Dc = defaultdict(int)
Exists = True

for i in range(S):
  D[s[i]].append(i+1)
  Dc[s[i]] += 1

ans = 0
temp = 0
for i in range(T):
  if D[t[i]] == []:
    Exists = False
    break
  j = bisect(D[t[i]], temp)
  if j == Dc[t[i]]:
    ans += S - temp + D[t[i]][0]
    temp = D[t[i]][0]
  else:
    ans += D[t[i]][j] - temp
    temp = D[t[i]][j]

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

s,t=input(),input()
if not set(list(t)) <=set (list(s)):print(-1);return
ss=[[]for i in range(26)]
for i,v in enumerate(s):ss[ord(v)-97].append(i)
nowind,loop=-1,0
from bisect import bisect_left as bl,bisect_right as br
for i in t:
    ind=ord(i)-97
    if ss[ind][-1]<nowind:
        nowind=-1
        loop+=1
    nowind=ss[ind][bl(ss[ind],nowind)]+1
print(loop*len(s)+nowind)

import bisect
S = input()
T = input()
D = dict()
for i in range(len(T)):
    if T[i] in D:
        continue
    else:
        D[T[i]] = []
for i in range(len(S)):
    if S[i] in D:
        D[S[i]].append(i)

if len(set(T)-set(S))>0:
    print(-1)
else:
    r = -1
    cnt = 0
    for i in range(len(T)):
        m = bisect.bisect_right(D[T[i]], r)
        if m < len(D[T[i]]):
            r = D[T[i]][m]
        else:
            r = D[T[i]][0]
            cnt += 1
    print(len(S)*cnt+r+1)

#!/usr/bin/env python3
import sys


def solve(s: str, t: str):
    """
    >>> solve("aaa", "aaa")
    3
    >>> solve("a", "a")
    1
    >>> solve("contest", "son")
    10
    """
    from collections import defaultdict
    from bisect import bisect
    d = defaultdict(list)
    for i, c in enumerate(s):
        d[c].append(i)
    ans, i = 0, -1
    for c in t:
        #print(ans, i, end=" ")
        if not d[c]:
            return -1
        j = bisect(d[c], i)
        if len(d[c]) == j:
            ans += len(s) - i + d[c][0]
            i = d[c][0]
        else:
            ans += d[c][j] - i
            i = d[c][j]
        #print("->", ans, i)
    return ans

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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
    print((solve(s, t)))

     
def test():
    import doctest
    doctest.testmod()

def __starting_point():
    test()
    main()

__starting_point()

from string import ascii_lowercase
from bisect import bisect_right, bisect_left


def main():
    s = input()
    t = input()
    len_s = len(s)
    s_all = {s: [] for s in ascii_lowercase}
    for i in range(len_s):
        s_all[s[i]].append(i + 1)
    ans = 0
    if any(s_all[tt] == [] for tt in t):
        ans = -1
    else:
        s_ind = 1
        for ss in ascii_lowercase:
            s_all[ss].sort()
        for i in range(len(t)):
            next_ind = bisect_left(s_all[t[i]], s_ind)
            if next_ind == len(s_all[t[i]]):
                ans += len_s - s_ind + 1
                ans += s_all[t[i]][0]
                s_ind = s_all[t[i]][0] + 1
            else:
                ans += s_all[t[i]][next_ind] - s_ind + 1
                s_ind = s_all[t[i]][next_ind] + 1
    print(ans)


def __starting_point():
    main()

__starting_point()

from bisect import bisect_right
s = input()
t = input()
alpha = [[] for _ in range(26)]
def f(c): return ord(c)-ord("a")


for i,c in enumerate(s): alpha[f(c)].append(i)
# print(alpha)
idx = -1
roop = 0
for c in t:
    lst = alpha[f(c)]
    if not lst:
        ans = -1
        break
    i = bisect_right(lst,idx)
    if i == len(lst):
        roop += 1
        idx = lst[0]
    else:
        idx = lst[i]
else:
    ans = len(s)*roop+idx+1
print(ans)

import sys
sys.setrecursionlimit(200000)
from collections import Counter, defaultdict
from bisect import bisect_left


def read():
    S = input().strip()
    T = input().strip()
    return S, T


def have_ahswer(S, T):
    cs = Counter(S)
    ct = Counter(T)
    for k in list(ct.keys()):
        if cs[k] == 0:
            return False
    return True


def solve(S, T):
    Z = "abcdefghijklmnopqrstuvwxyz"
    if not have_ahswer(S, T):
        return -1
    D = defaultdict(list)
    for i, s in enumerate(S):
        D[s].append(i)
    ans = 0
    prev_index = -1
    N = len(S)
    for t in T:
        a = D[t]
        i = bisect_left(a, prev_index + 1)
        if i < len(a):
            next_index = a[i]
            ans += next_index - prev_index
        else:
            next_index = a[0]
            ans += N + next_index - prev_index
        prev_index = next_index
    return ans


def __starting_point():
    inputs = read()
    print(("{}".format(solve(*inputs))))

__starting_point()

import bisect

en2asc = lambda s: ord(s) - 97

S = input()
T = input()
if not set(S) >= set(T):
    print(-1)
    return

lst = [[] for _ in range(26)]
for i, s in enumerate(S):
    lst[en2asc(s)].append(i)

L = len(S)
cur = 0
for t in T:
    t = en2asc(t)
    b = bisect.bisect_left(lst[t], cur % L)
    if b == len(lst[t]):
        cur = (cur // L + 1) * L
        b = bisect.bisect_left(lst[t], cur % L)
    cur = cur // L * L + lst[t][b] + 1
print(cur)

import sys
import math
import bisect
import heapq
from collections import defaultdict

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

from collections import defaultdict
from bisect import bisect_left
s = input()
t = input()
ids = defaultdict(list)
for i, c in enumerate(s):
    ids[c].append(i)
i = 0
ans = 0
for c in t:
    if c not in ids:
        print(-1)
        return
    ls = ids[c]
    j = bisect_left(ls, i)
    if j == len(ls):
        ans += len(s)
        i = ls[0]+1
    else:
        i = ls[j]+1
print(ans+i)

"""
Tの文字にたいして、Sのインデックスをリストで持たせる
Tの頭から順繰りにたし上げていく（Loop数を数えること）
自分よりも大きい要素があれば、それを使うし、
なければ最も小さい要素を使いつつ、Loop数をCountUp
bisect_left()かな？

0123456
contest

01234567
sentence

s=[5]   -> 5  (6moji)
e=[4]   -> 7*1+4 (12moji)
n=[2]   -> 7*2+2 = 16
t=[3,6] -> 7*2+3 = 17
e=[4]   -> 7*2+4 = 18
n=[2]   -> 7*3+2 = 23
c=[0]   -> 7*4+0 = 28
e=[4]   -> 7*4+4 = 32 ( 33moji)
"""

from bisect import bisect_right, bisect_left
S = input()
T = input()

def calc(ch):
  return ord(ch) - ord('a')

## Tに含まれる文字に対し、Sのインデックスをふる
LST = [[] for _ in range(26)]
for t in T:
  nt = calc(t)
  if len(LST[nt]) > 0:
    continue
  for i in range(len(S)):
    if t == S[i]:
      LST[nt].append(i)
  if len(LST[nt]) == 0:
    print(-1)
    return
    
NS = len(S)
## Tの文字に対して順繰りにたしあげる
NofLoop = 0
now = 0
for i in range(len(T)):
  t = T[i]
  nt = calc(t)
  rel_now = now - NofLoop * NS
  if rel_now < LST[nt][0] :
    #print("R",t,nt,rel_now)
    now = NofLoop * NS + LST[nt][0] + 1
  elif LST[nt][-1] < rel_now :
    #print(t,i)
    NofLoop += 1
    now = NofLoop * NS + LST[nt][0] + 1
  else:
    idx = bisect_left(LST[nt], rel_now)
    #print(idx)
    now = NofLoop * NS + LST[nt][idx] + 1
    
print(now)

s = input()
t = input()
if set(t) & set(s) == set(t):
    n = -1
    c = 0
    for i in t:
        n = s.find(i, n + 1)
        if n == -1:
            c += 1
            n = s.find(i)
    print(n + len(s) * c + 1)
else:
    print(-1)

import sys
import math
from collections import deque
import bisect

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    S = SI()
    T = SI()
    if set(S) | set(T) != set(S):
        print(-1)
        return
    s2i = {}

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

    now = 0
    digit = -1
    for t in T:
        target = bisect.bisect_right(s2i[t], digit)
        if target == len(s2i[t]):
            digit = s2i[t][0]
            now += 1
        else:
            digit = s2i[t][target]

    print(now * len(S) + digit + 1)


def __starting_point():
    main()
__starting_point()

import bisect
from collections import defaultdict

s = input()
t = input()
if set(s) & set(t) != set(t):
    print((-1))
    return
cnt = defaultdict(list)
for i, c in enumerate(s, 1):
    cnt[c].append(i)
loop = 0
prev = 0
for w in t:
    l = cnt[w]
    idx = bisect.bisect_right(l, prev)
    if idx < len(l):
        prev = l[idx]
    else:
        prev = l[0]
        loop += 1
ans = loop*len(s) + prev
print(ans)


from bisect import bisect_left

S = input()
T = input()

ss = set(list(S))
st = set(list(T))
if not (st <= ss):
    print((-1))
    return
alpha = {chr(97+i): [] for i in range(26)}
for i, s in enumerate(S):
    alpha[s].append(i+1)
n = len(S)
now = 0
ans = 0
for t in T:
    if alpha[t][-1] <= now:
        ans += (n - now) + alpha[t][0]
        now = alpha[t][0]
    else:
        i = bisect_left(alpha[t], now+1)
        ans += alpha[t][i] - now
        now = alpha[t][i]
print(ans)


s = input()
t = input()
n = len(s)
s += s
# pos[i][j] := 場所iの次に現れる最も近いj(文字)のインデックス
pos = [[-1] * 26 for _ in range(n * 2 + 1)]
for i in range(n * 2 - 1, -1, -1):
    k = ord(s[i]) - ord('a')
    for j in range(26):
        if j == k:
            pos[i][j] = i
        else:
            pos[i][j] = pos[i + 1][j]

ans = 0
now = 0
for c in t:
    x = ord(c) - ord('a')
    if pos[now][x] == -1:
        print((-1))
        return
    ans += -~pos[now][x] - now
    now = -~pos[now][x] % n
print(ans)


from bisect import bisect_right
s = input()
t = input()
alpha = [[] for _ in range(26)]
def f(c): return ord(c)-ord("a")

for i,c in enumerate(s): alpha[f(c)].append(i)
idx = -1
loop = 0
for c in t:
    lst = alpha[f(c)]
    if not lst:
        ans = -1
        break
    i = bisect_right(lst,idx)
    if i == len(lst):
        loop += 1
        idx = lst[0]
    else:
        idx = lst[i]
else:
    ans = len(s)*loop+idx+1
print(ans)

import sys
readline = sys.stdin.readline

S = readline().rstrip()
T = readline().rstrip()

if len(set(T) - set(S)) > 0:
  print(-1)
  return
  
import bisect
S2 = S * 2
from collections import defaultdict
dic = defaultdict(list)

for i in range(len(S2)):
  dic[S2[i]] += [i]

ind = -1
ans = 0
for t in T:
  targets = dic[t]
  newind = targets[bisect.bisect_left(targets, ind + 1)]
  ans += (newind - ind)
  if newind >= len(S):
    newind -= len(S)
  ind = newind

print(ans)

import math
import heapq
import bisect
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

from bisect import bisect_left


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

    pos = {c: [] for c in "abcdefghijklmnopqrstuvwxyz"}
    for i, c in enumerate(S):
        pos[c].append(i)
    ans = 0
    cur_pos = 0
    for t in T:
        nxt_idx = bisect_left(pos[t], cur_pos)
        if nxt_idx == len(pos[t]):
            ans += len(S)
            cur_pos = 0
            nxt_idx = bisect_left(pos[t], cur_pos)
            cur_pos = pos[t][nxt_idx] + 1
        else:
            cur_pos = pos[t][nxt_idx] + 1

    return ans + cur_pos


print((solve()))


import sys
from collections import defaultdict
from bisect import bisect_right

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    S = input()
    n = len(S)
    T = input()

    pos = defaultdict(list)
    for i in range(n):
        pos[S[i]].append(i + 1)

    res = 0
    now = 0
    for t in T:
        if pos.get(t, -1) == -1:
            print((-1))
            return
        idx = bisect_right(pos[t], now)
        if len(pos[t]) == idx:
            res += n - now + pos[t][0]
            now = pos[t][0]
        else:
            res += pos[t][idx] - now
            now = pos[t][idx]
    print(res)


def __starting_point():
    resolve()

__starting_point()

from bisect import bisect_left
from string import ascii_lowercase

s = input()
t = input()
n = len(s)

dict_s = {c: [] for c in ascii_lowercase}
for i, c in enumerate(s * 2):
    dict_s[c].append(i)

for c in ascii_lowercase:
    if not dict_s[c]:
        del dict_s[c]


dict_next_i = {
    c: [dict_s[c][bisect_left(dict_s[c], i + 1)] for i in range(n)]
    for c in list(dict_s.keys())
}


def next_i(i, c):
    return n * (i // n) + dict_next_i[c][i % n]


def answer():
    if not all(c in s for c in t):
        return -1
    i = -1
    for c in t:
        i = next_i(i, c)
    return i + 1  # 1-origin


print((answer()))


#!/usr/bin/env python3
 
import sys
# 以下を記述しないとTLEになる, 何故？
from heapq import heappushpop, heapify, heapreplace
from collections import defaultdict
# ---- ここまで -----------------------
 
S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return
 
ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1
 
print(ans)

from bisect import bisect_left,bisect
s = list(input())
sn = len(s)
t = list(input())
tn = len(t)
kouho = []
for i in range(26):
    kar = []
    now = chr(ord('a') + i)
    for j in range(sn):
        if s[j] == now:
            kar.append(j)
    kouho.append(kar)

cou = 0
now = -1
for i in range(tn):
    u = ord(t[i])-ord("a")
    if kouho[u]:
        tugi = bisect(kouho[u],now)
        if tugi == len(kouho[u]):
            cou += 1
            now = kouho[u][0]
        else:
            now = kouho[u][tugi]
    else:
        print(-1)
        return

print(cou*sn + now + 1)

import bisect

s = input()
t = input()
n = len(s)
s += s

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

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

ans = 0
now = -1
for i in range(len(t)):
    c = ord(t[i]) - ord('a')
    j = bisect.bisect_right(pos[c], now)

    if j == len(pos[c]):
        print((-1))
        return
    now = pos[c][j]

    if now >= n:
        now -= n
        ans += n
print((ans + now + 1))


from bisect import bisect_left as bisect
from collections import defaultdict


s, t = input(), input()
lens, sets = len(s), set(s)

if not all(i in sets for i in t):
    print((-1))
    return

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

ans, cnt = 1 - lens, 0
for i in t:
    ans += lens * (cnt == 0)
    num = bisect(alp[i], cnt)
    ans += lens * (num == len(alp[i]))
    cnt = (alp[i][num % len(alp[i])] + 1) % lens 
print((ans + (cnt - 1) % lens))


from collections import defaultdict
import bisect
s, t = [x.strip() for x in open(0).readlines()]
if set(t) - set(s) != set():
    print(-1)
else:
    d = defaultdict(list)
    n = len(s)
    for i, c in enumerate(s, 1):
        d[c].append(i)
    for k in d:
        d[k].append(d[k][0] + n)
    ans = 0
    for c in t:
        q, r = divmod(ans, n)
        x = d[c][bisect.bisect(d[c], r)]
        ans = n*q + x
    print(ans)

from collections import defaultdict
import bisect
def solve():
    s = input()
    t = input()
    d = defaultdict(list)
    st_s = set(s)

    for i in range(len(s)):
        d[s[i]].append(i)
    
    round = 0
    prev = -1
    for i in range(len(t)):
        if not t[i] in st_s:
            print(-1)
            return
        now = getNextIdx(prev,d[t[i]])
        if now <= prev:
            round += 1
        
        prev = now
    
    print(prev + round*len(s) + 1)

def getNextIdx(prev,idx_list):
    ret_idx = bisect.bisect_right(idx_list, prev)
    if ret_idx == len(idx_list):
        return idx_list[0]

    return idx_list[ret_idx]

def __starting_point():
    solve()
__starting_point()

s = input()
t = input()
l_s = len(s)
l_t = len(t)

s2 = s + s
l_s2 = len(s2)

next_idx = [[l_s2] * 26 for i in range(l_s2)]

for i in reversed(range(1, l_s2)):
    for j in range(26):
        next_idx[i-1][j] = next_idx[i][j]
    next_idx[i-1][ord(s2[i]) - ord("a")] = i

cur_idx = 0
for i in range(l_t):
    if i == 0:
        flg = False
        for j in range(l_s):
            if t[i] == s[j]:
                cur_idx += j
                flg = True
                break
        if flg:
            continue
        else:
            print("-1")
            return

    else:
        idx = next_idx[cur_idx%l_s][ord(t[i]) - ord("a")]

    if idx == l_s2:
        print("-1")
        return

    cur_idx += idx - (cur_idx % l_s)
    
print(cur_idx+1)

import bisect

s=input()
t=input()
n=len(s)*2

dic={}
for idx,i in enumerate(s*2):
  if i in dic.keys():
    dic[i].append(idx)
  else:
    dic[i]=[idx]

#print(dic)
    
ans=k=0
before='-1'
for i in t:
  if i not in dic.keys():
    print(-1)
    return
  t=bisect.bisect_left(dic[i], ans%n)
  if before==i:
    t+=1
  if len(dic[i])==t:
    t=0
    k+=n
  ans=dic[i][t]+k
  before=i
  
print(ans+1)

from collections import Counter, defaultdict
from bisect import bisect_right

s = input()
t = input()

c = Counter(s)
for e in t:
    if c[e] == 0:
        print((-1))
        return

ss = s + s
d = defaultdict(list)
for i, e in enumerate(ss):
    d[e].append(i)

now = -1
ans = 0
for e in t:
    i = bisect_right(d[e], now)
    nxt = d[e][i]
    ans += nxt - now
    now = nxt % len(s)

print(ans)


def solve():
  s = input()
  t = input()
  ans = 0
  alp = [[] for _ in range(27)]
  length_s = len(s)
  for i in range(length_s):
    char = ord(s[i]) - ord('a')
    alp[char].append(i + 1)
  length_t = len(t)
  import bisect
  for i in range(length_t):
    char = ord(t[i]) - ord('a')
    if alp[char]:
      if ans % length_s >= alp[char][-1]:
        ans = (ans // length_s + 1) * length_s
      index = bisect.bisect_right(alp[char], ans % length_s)
      ans += alp[char][index] - ans % length_s
    else:
      return -1
  return ans
print(solve())

# -*- coding: utf-8 -*-
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
import copy
import math
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz(): return list(map(int, sys.stdin.readline().split()))


def z(): return int(sys.stdin.readline())


def S(): return sys.stdin.readline()[:-1]


def C(line): return [sys.stdin.readline() for _ in range(line)]


s = S()
t = S()
set_s = set(s)
set_t = set(t)
if (set_t <= set_s) is False:
    print((-1))
    return
alphabet2index = defaultdict(list)
for i, alphabet in enumerate(s):
    alphabet2index[alphabet].append(i+1)
ans = 0
pos = 0
prev_pos = 0
base = 0
n = -1
c = 0
for _t in t:
    n = s.find(_t, n+1)
    if (n == -1):
        c += 1
        n = s.find(_t)
ans = n + c*len(s) + 1
"""

    ng_flg = True
    while ng_flg:
        pos_lis = alphabet2index[_t]
        i = 0
        while len(pos_lis) > i:
            if (pos_lis[i] >= pos):
                pos = pos_lis[i]
                ans += (pos_lis[i]-prev_pos)
                # print(pos_lis[i], prev_pos, )
                prev_pos = pos
                ng_flg = False
                break
            i += 1
        else:
            prev_pos = pos - len(s)
            # print(prev_pos)
            # print('base', base)
            pos = 0
    """
print(ans)


import collections,math
s = input()
t = input()
#tを構成文字で、sにない文字があったらダメ。
#構成できるなら最大でもlen(t)個しかないから、10^100の連結は必要ない

#最も不足する文字を探す
ls = collections.Counter(s)
lt = collections.Counter(t)

time_dict ={}
tmp=0
max_time=0#一番少ないやつ
for t_key,t_val in list(lt.items()):
    if t_key not in ls:#sの中にtの文字がない
        print((-1))
        return

#多分TLEするかも。。
cnt = 0
tt = list(t[::-1])
idx=0
ss = s
while tt!=[]:
    next_t = tt.pop()
    idx=ss.find(next_t)
    if idx == -1:
        cnt += len(ss)
        idx = s.find(next_t)
        ss = s[idx+1:]
        cnt += idx+1
    else:
        cnt += idx+1
        ss = ss[idx+1:]
print(cnt)


from bisect import bisect_left
from string import ascii_lowercase


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

    set_s = set(tuple(s))
    set_t = set(tuple(t))

    if not(set_t <= set_s):
        print(-1)
        return

    ans = 0
    d = {c:[] for c in ascii_lowercase}
    
    for i, c in enumerate(s):
        d[c].append(i+1)
    
    now = 0
    for c in t:
        
        idx = bisect_left(d[c], now+1)

        if idx == len(d[c]):
            ans += len(s)
            now = 0
            idx = bisect_left(d[c], now+1)
            
        now = d[c][idx]

    ans += now
    print(ans)

        
def __starting_point():
    main()
__starting_point()

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

S_ = set(list(S))
T_ = set(list(T))
for c in T:
    if c not in S_:
        print((-1))
        return

d = [[] for _ in range(26)]
for i, s in enumerate(S):
    d[ord(s)-ord('a')].append(i)
#print(d)

q = 0
pre = -1
import bisect
for t in T:
    j = ord(t)-ord('a')
    idx = bisect.bisect_right(d[j], pre)
    if idx == len(d[j]):
        q += 1
        pre = d[j][0]
    else:
        pre = d[j][idx]
print((q*len(S)+pre+1))


from bisect import bisect
s = list(input())
t = list(input())
lenT = len(t)
lenS = len(s)
alp = []

for i in range(26):
  array = []
  now = chr(ord('a') + i)
  for j in range(lenS):
    if s[j] == now:
      array.append(j)
  alp.append(array)

count,now = 0,-1

for i in range(lenT):
  j = ord(t[i])-ord('a')
  if alp[j]:
    next = bisect(alp[j],now)
    if next == len(alp[j]):
      count += 1
      now = alp[j][0]
    else:
      now = alp[j][next]
  else:
    print(-1)
    return

ans = count*lenS+now+1

print(ans)

from collections import Counter,defaultdict
import bisect

s = input()
t = input()
ss = s*2

S = Counter(s)
T = Counter(t)

for i in T.keys():
    if i not in S:
        print(-1)
        return

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

for i,j in enumerate(ss):
    alpha[ord(j)-ord("a")].append(i)

rep,now = 0,-1

for i in t:
    alp = alpha[ord(i) - ord('a')]
    i = bisect.bisect_left(alp,now+1)
    now = alp[i]
    if now >= len(s):
        now -= len(s)
        rep += 1

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

from bisect import bisect_right
s = input()
t = input()

n = len(s)

if set(list(t)) != (set(list(s)) & set(list(t))): ans = -1
else:
    dct = {}

    for i, ss in enumerate(s):
        if ss in dct:
            dct[ss].append(i)
        else: dct[ss] = [i]
    idx = -1
    ans = 0
    for tt in t:
        m = bisect_right(dct[tt], idx)
        if m == len(dct[tt]):
            idx = dct[tt][0]
            ans += n
        else:
            idx = dct[tt][m]
    ans += idx + 1

print(ans)

import math
import heapq
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

import collections

s = input()
t = input()
mod = len(s)
s_idx = dict([])
for i, key in enumerate(s):
    try:
        s_idx[key].append(i + 1)
    except KeyError:
        s_idx[key] = [i + 1]

def binary_search(li, tmp, ng, ok):
    mid = (ng + ok) // 2
    if ok - ng < 2:
        if ok == len(li):
            return mod + li[0]
        else:
            return li[ok]
    if li[mid] <= tmp: return binary_search(li, tmp, mid, ok)
    else: return binary_search(li, tmp, ng, mid)

ans = 0
tmp = 0
for key in t:
    try:
        i = binary_search(s_idx[key], tmp, -1, len(s_idx[key]))
        ans += i - tmp
        tmp = i % mod
    except KeyError:
        ans = -1
        break
print(ans)

import string
import bisect
s=input()
t=input()
S=[[] for _ in range(26)]
a=string.ascii_lowercase
now=-1
ans=-1
count=0
for i in range(len(s)):
    for j in range(26):
        if s[i]==a[j]:
            S[j].append(i)
            break
for i in range(len(t)):
    for j in range(26):
        if t[i]==a[j]:
            break
    if len(S[j])==0:
        break
    nex=bisect.bisect_right(S[j],now)
    if nex==len(S[j]) or now>=S[j][nex]:
        count+=1
        now=S[j][0]
    else:
        now=S[j][nex]
    if i==len(t)-1:
        ans=count*(len(s))+now+1
print(ans)

from bisect import bisect

def ctoi(c):
    return ord(c) - ord('a')

def solve():
    S = input()
    T = input()
    N = len(S)
    idx = [[] for i in range(26)]
    for i in range(2 * N):
        idx[ctoi(S[i % N])].append(i)
    ans = -1
    for c in T:
        if not idx[ctoi(c)]:
            return -1
        ans += idx[ctoi(c)][bisect(idx[ctoi(c)], ans % N)] - ans % N
    return ans + 1
print((solve()))


#このプログラムはpypyじゃ通らない
import collections,math
s = input()
t = input()
#tを構成文字で、sにない文字があったらダメ。
#構成できるなら最大でもlen(t)個しかないから、10^100の連結は必要ない

#最も不足する文字を探す
ls = collections.Counter(s)
lt = collections.Counter(t)

time_dict ={}
tmp=0
max_time=0#一番少ないやつ
for t_key,t_val in list(lt.items()):
    if t_key not in ls:#sの中にtの文字がない
        print((-1))
        return

#文字をカウントしていく
cnt = 0
tt = list(t[::-1])#指定したい文字へのアクセス時間を1にしたいので反転
idx=0
ss = s#ssは検索文字列
while tt!=[]:#ttが空っぽになったらおしまい
    next_t = tt.pop()#つぎに構成したい文字= next_t
    idx=ss.find(next_t)#検索文字列にnext_tがあるか
    if idx == -1:#ない
        cnt += len(ss)#検索文字列の長さを全部足す
        idx = s.find(next_t)#新たにsを検索文字列として探す
        ss = s[idx+1:]#next_t以降の文字列を次回の検索文字列をセット
        cnt += idx+1 #nex_tが見つかった文字までの長さ
    else:#ある
        cnt += idx+1 #文字長さを足す 
        ss = ss[idx+1:]#次回の検索文字列をセット
print(cnt)


import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: list(map(int, sys.stdin.readline().split()))
na = lambda: list(map(int, sys.stdin.readline().split()))
nb = lambda: list([int(x) - 1 for x in sys.stdin.readline().split()])


# ===CODE===


def main():
    s = list(input())
    t = collections.deque(list(input()))

    jump = [[0] * 26 for _ in range(len(s) + 1)]

    for i in range(len(s) - 1, -1, -1):
        jump[i] = jump[i + 1].copy()
        jump[i][ord(s[i]) - 97] = i + 1

    ans = 0
    point = 0
    while len(t) > 0:
        tmp = t.popleft()
        character = ord(tmp) - 97
        if jump[point][character] == 0 and point == 0:
            print((-1))
            return
        point = jump[point][character]
        if point == 0:
            t.appendleft(tmp)
            ans += 1

    print((ans * len(s) + point))


def __starting_point():
    main()

__starting_point()

import bisect
ind = {}
s = input()
t = input()
for i, c in enumerate(s):
    if c in ind:
        ind[c].append(i+1)
    else:
        ind[c] = [i+1]
k = len(s)
nk = 0
if not t[0] in ind:
    print(-1)
    return
nw = ind[t[0]][0]
pv = nw
for i in range(1, len(t)):
    c = t[i]
    if not c in ind:
        print(-1)
        return
    if ind[c][-1]>pv:
        pv = ind[c][bisect.bisect_left(ind[c], pv+1)]
    else:
        nk += k
        pv = ind[c][0]
    nw = pv + nk
print(nw)

def solve():
    S = input()
    T = input()
    N = len(S)
    M = 2 * N
    S += S
    nxt = [[M] * 26 for i in range(M + 1)]
    for i in range(M - 1, -1, -1):
        for j in range(26):
            nxt[i][j] = nxt[i + 1][j]
        nxt[i][ord(S[i]) - ord('a')] = i
    ans = 0
    i = 0
    for c in T:
        pos = ord(c) - ord('a')
        if nxt[i][pos] == M:
            return -1
        ans += nxt[i][pos] - i + 1
        i = (nxt[i][pos] + 1) % N
    return ans

print((solve()))


def find(base, indexes):
    n = len(indexes)
    ng = -1
    ok = n

    while ok - ng > 1:
        mid = (ok + ng) // 2
        if indexes[mid] > base:
            ok = mid
        else:
            ng = mid

    return indexes[0] if ok == n else indexes[ok]


s = input()
t = input()

s_set = set(s)
t_set = set(t)

if t_set.issubset(s_set) is False:
    print((-1))
    return

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

for i in range(len(s)):
    c = s[i]
    idx = ord(c) - ord("a")
    s_indxes[idx].append(i)

base = -1
loop = 0
for i in range(len(t)):
    c = t[i]
    idx = ord(c) - ord("a")
    n_base = find(base, s_indxes[idx])

    if n_base <= base:
        loop += 1

    base = n_base

print((loop * len(s) + base + 1))


#!/usr/bin/env python3
from bisect import bisect_right

s = input()
N = len(s)
si = [[] for _ in range(26)]
for i in range(N):
    si[ord(s[i])-ord('a')].append(i+1)

ans = 0
t = input()
M = len(t)
for j in range(M):
    ti = si[ord(t[j])-ord('a')]
    if len(ti)==0:
        print(-1)
        return
    d = bisect_right(ti,ans%N)
    if d == len(ti):
        ans += ti[0]+N-ans%N
    else:
        ans += ti[d]-ans%N
print(ans)

from bisect import bisect_right
s = tuple(map(lambda c: ord(c) - ord("a"), input()))
t = tuple(map(lambda c: ord(c) - ord("a"), input()))
S, T = set(s), set(t)
if T & S != T:
    print(-1)
    return
d, l = [[] for _ in range(26)], [0] * 26
for idx, c in enumerate(s):
    d[c].append(idx)
    l[c] += 1
prev = -1
loop = 0
for c in t:
    idx = bisect_right(d[c], prev)
    if idx >= l[c]:
        loop += 1
        prev = d[c][0]
    else:
        prev = d[c][idx]
print((loop) * len(s) + prev + 1)

from bisect import bisect_left
from collections import defaultdict as dd

def main():

  s=input()
  t=input()
  n=len(s)

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

  ans,p=0,-1
  for i in t:
    if i not in dic.keys():
      print(-1)
      return
    p=dic[i][bisect_left(dic[i], p+1)]
    if p>=n:
      p-=n
      ans+=n

  print(ans+p+1)

def __starting_point():
  main()
__starting_point()

import sys
from string import ascii_lowercase as a2z

input = sys.stdin.readline


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

    N = len(S)
    memo = [None] * N
    memo[-1] = {alphabet: -1 for alphabet in a2z}
    memo[-1][S[-1]] = N - 1
    for i in reversed(list(range(N - 1))):
        memo[i] = memo[i + 1].copy()
        memo[i][S[i]] = i

    ans = 0
    idx_S = 0
    for t in T:
        i = memo[idx_S][t]
        if i == -1:
            ans += (N - idx_S)
            idx_S = 0
            i = memo[idx_S][t]
            if i == -1:
                ans = -1
                break
            else:
                ans += i - idx_S + 1
                if i == N - 1:
                    idx_S = 0
                else:
                    idx_S = i + 1
        else:
            ans += i - idx_S + 1
            if i == N - 1:
                idx_S = 0
            else:
                idx_S = i + 1

    print(ans)


def __starting_point():
    main()

__starting_point()

import bisect

s=input()
t=input()
n=len(s)

dic={}
for idx,i in enumerate(s*2):
  if i in dic.keys():
    dic[i].append(idx)
  else:
    dic[i]=[idx]

ans,p=0,-1
for i in t:
  if i not in dic.keys():
    print(-1)
    return
  p=dic[i][bisect.bisect_left(dic[i], p+1)]
  if p>=n:
    p-=n
    ans+=n
  
print(ans+p+1)

A = tuple(range(10**5))

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print((-1))
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)


from collections import Counter
import bisect

s = input()
t = input()
"""
TLE問題なのは間違いないが、工夫も結構厳しい必要がありそう
二分探索を用いれば, O(|t| log|s|)の定数倍で解ける？
"""

# 絶対に作れないやつは-1を出す、それ以外は絶対に作れる.
sc = Counter(s)
tc = Counter(t)
for i, j in tc.most_common():
	if sc[i] == 0:
		print(-1)
		return

"""
O(|t| |s|)で解けるが、TLE確実.
bisectを使う。
"""

target = ord("a")
ordl = [[] for _ in range(26)]
for i, j in enumerate(s):
	ordl[ord(j)-target].append(i)
ordllen = [len(ordl[i]) for i in range(26)]

# ordl := 各文字のindex番号.

times = 0
cnt = -1
ans = 0
for i in t:
	k = ord(i)-target
	m = bisect.bisect_right(ordl[k], cnt)
	if m == ordllen[k]:
		times += 1
		cnt = ordl[k][0]
	else:
		cnt = ordl[k][m]

ans = times * len(s) + cnt + 1
print(ans)

import bisect

def ctoi(char):
  return ord(char)-ord('a')

s=input()
l=len(s)
t=input()
if len(set(t)-set(s))!=0:
  print(-1)
  return
pos=[[] for _ in range(26)]
for i in range(2*l):
  pos[ctoi(s[i%l])].append(i+1)
index=0
loop=0
for i in range(len(t)):
  tmp=bisect.bisect_right(pos[ctoi(t[i])],index)
  next_index=pos[ctoi(t[i])][tmp]
  if next_index>=l:
    loop+=1
  index=next_index%l
print(l*loop+index)

import sys
readline = sys.stdin.readline

S = readline().rstrip()
T = readline().rstrip()

if len(set(T) - set(S)) > 0:
  print(-1)
  return
  
import bisect
# Tの各文字を探す
S2 = S * 2
from collections import defaultdict
# ある文字が何文字目にあるか辞書
dic = defaultdict(list)

for i in range(len(S2)):
  dic[S2[i]] += [i]

ind = -1
ans = 0
for t in T:
  # 探す文字はt
  targets = dic[t]
#  print("targets",targets,"t",t,"ind + 1",ind + 1)
  newind = targets[bisect.bisect_left(targets, ind + 1)]
#  print("t",t,"S2",S2,"newind",newind)
  ans += (newind - ind)
  if newind >= len(S):
    newind -= len(S)
  ind = newind

print(ans)

from bisect import *
def alph_to_num(s):
  return ord(s)-ord('a')
def solve():
  ans = 0
  S = input()
  T = input()
  lis = [[] for _ in range(26)]
  for i,s in enumerate(S):
    lis[alph_to_num(s)].append(i)
  ind = -1
  for t in T:
    n = alph_to_num(t)
    if not len(lis[n]):
      return -1
    if ind>=lis[n][-1]:
      ans += len(S)
      ind = lis[n][0]
    else:
      ind = lis[n][bisect_right(lis[n],ind)]
  ans += ind+1
  return ans
print(solve())

'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7

def main():
    s = input()
    ls = len(s)
    t = input()
    if t[0] in s:
        idx = s.find(t[0])
    else:
        print((-1))
        return
    for i in t[1::]:
        nt = s.find(i,idx%ls+1)
        ntl = s.find(i)
        if ntl == -1:
            print((-1))
            return
        elif nt == -1:
            idx = (idx//ls)*ls+ls+ntl
        else:
            idx = (idx//ls)*ls+nt
    print((idx+1))
    return None

def __starting_point():
    main()

__starting_point()

S = input()
T = input()

from collections import defaultdict

nx = [defaultdict(lambda: -1) for i in range(len(S)+1)]
lastpos = defaultdict(lambda: 0)

SS = S+S
for i,c in enumerate(SS[::-1]):
    i = len(SS)-1-i
    if i < len(S):
        for k,v in lastpos.items():
            nx[i+1][k] = v-i
    lastpos[c] = i
for k,v in lastpos.items():
    nx[0][k] = v+1

ans = 0
for c in T:
    if nx[ans%len(S)][c] == -1:
        print(-1)
        return
    ans += nx[ans%len(S)][c]
print(ans)

import bisect
from collections import defaultdict
s = input()
n = len(s)
t = input()
if set(s) & set(t) != set(t):
    print((-1))
else:
    cnt = defaultdict(list)
    for i in range(n):
        cnt[s[i]].append(i+1)
    loop = 0
    prev = 0
    for c in t:
        x = cnt[c]
        idx = bisect.bisect_right(x, prev)
        if idx < len(x):
            prev = x[idx]
        else:
            prev = x[0]
            loop += 1
    print((loop*n+prev))


def abc138_e():
    s = str(input())
    t = str(input())
    sd = dict()
    for i, c in enumerate(s):
        if sd.get(c) == None: sd[c] = []
        sd[c].append(i)
    from bisect import bisect_left
    k = 0
    p = 0
    for c in t:
        if sd.get(c) == None: return print(-1)
        idx = bisect_left(sd[c], p)
        if idx == len(sd[c]):
            k += 1
            p = 0
            idx = bisect_left(sd[c], p)
        p = sd[c][idx] + 1
    ans = k * len(s) + p
    return print(ans)

def __starting_point():
    abc138_e()
__starting_point()

import heapq
import bisect
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

import collections

s = input()
t = input()
s_len = len(s)
s_idx = dict([])
for i, key in enumerate(s):
    try:
        s_idx[key].append(i + 1)
    except KeyError:
        s_idx[key] = [i + 1]

def binary_search(li, tmp, ng, ok):
    mid = (ng + ok) // 2
    if ok - ng < 2:
        if ok == len(li):
            return s_len + li[0]
        else:
            return li[ok]
    if li[mid] <= tmp: return binary_search(li, tmp, mid, ok)
    else: return binary_search(li, tmp, ng, mid)

ans = 0
ex_i = 0
for key in t:
    try:
        i = binary_search(s_idx[key], ex_i, -1, len(s_idx[key]))
        ans += i - ex_i
        ex_i = i % s_len
    except KeyError:
        ans = -1
        break
print(ans)

s=input()
t=input()

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

len_s=len(s)
len_t=len(t)


for i in range(len_s):
    idx=ord(s[i])-97
    pos[idx].append(i)

ans=[]
tmp=-1
cnt=0
for i in range(len_t):
    idx=ord(t[i])-97
    if len(pos[idx])==0:
        print((-1))
        return

    if tmp<pos[idx][-1]:
        l=-1
        r = len(pos[idx]) - 1
        while l + 1 < r:
            mid = (l + r) // 2
            if pos[idx][mid] <= tmp:
                l = mid
            else:
                r=mid
        ans.append(pos[idx][r])
        tmp=pos[idx][r]
    else:
        cnt+=1
        ans.append(pos[idx][0])
        tmp=pos[idx][0]


print((cnt*len_s+ans[-1]+1))




import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=998244353
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  s=S()
  n=len(s)
  t=S()
  n2=len(t)

  d={}
  for i,x in enumerate(s):
    if x in d:
      y=d[x]
      y.append(i)
      d[x]=y
    else:
      d[x]=[i]

  # print(d)
  i=0
  j=0
  ans=1
  while j<n2:
    check=t[j]
    if check not in d:
      return -1
    l=d[check]
    if i<l[0]:
      ans+=l[0]-i+1
      i=l[0]+1
      j+=1
    elif l[-1]<i:
      ans+=n-(i+1)+l[0]+2
      i=l[0]+1
      j+=1
    else:
      if i==l[0]:
        ans+=1
        i+=1
        j+=1
      elif i==l[-1]:
        ans+=1
        i+=1
        j+=1
      else:
        left=0
        right=len(l)
        while right-left>1:
          m=(right+left)//2
          if l[m]>=i:
            right=m
          else:
            left=m
          # print(right,left,m,i)
        ans+=l[right]-i+1
        i=l[right]+1
        j+=1

    # print(i,ans)

    i%=n

  return ans-1

# main()
print((main()))


import copy

s = input()
t = input()

sn = len(s)
tn = len(t)
a = [[] for i in range(26)]
for i in range(sn):
    num = ord(s[i]) - 97
    a[num].append(i)

table = [[0]*sn for i in range(26)]
for i in range(26):
    if a[i]:
        table[i][:] = [copy.deepcopy(a[i][0])]*sn
    f = 0
    for j in a[i]:
        table[i][f:j] = [copy.deepcopy(j)]*(j-f)
        f = copy.deepcopy(j)

flg = True
cnt = 0 # 今何週したか
x = -1 # 今何文字目か
for i in range(tn):
    num = ord(t[i]) - 97
    # sの中に対象の文字が存在しない
    if not a[num]:
        flg = False
        break
    # sの中に対象の文字が存在
    xx = copy.deepcopy(x)
    x = table[num][x]
    if xx >= x:
        cnt += 1
print(cnt*sn + x+1) if flg else print(-1)

from bisect import bisect_right
s = input()
t = input()
alpha = [[] for _ in range(26)]
def f(c): return ord(c)-ord("a")

for i,c in enumerate(s): alpha[f(c)].append(i)
idx = -1
roop = 0
for c in t:
    lst = alpha[f(c)]
    if not lst:
        ans = -1
        break
    i = bisect_right(lst,idx)
    if i == len(lst):
        roop += 1
        idx = lst[0]
    else:
        idx = lst[i]
else:
    ans = len(s)*roop+idx+1
print(ans)

import bisect


def main() -> None:
    S = input()
    T = input()
    SS = S + S
    alphas = [[] for _ in range(26)]
    for i, s in enumerate(SS):
        alphas[ord(s) - ord('a')].append(i)
    rep, now = 0, -1
    for t in T:
        alpha = alphas[ord(t) - ord('a')]
        i = bisect.bisect_left(alpha, now + 1)
        if i == len(alpha):
            print((-1))
            return
        now = alpha[i]
        if now >= len(S):
            now -= len(S)
            rep += 1
    print((rep * len(S) + now + 1))



def __starting_point():
    main()

__starting_point()

import sys
from collections import defaultdict
import bisect
def input(): return sys.stdin.readline().rstrip()


def main():
    s = list(input())
    t = list(input())
    dic = defaultdict(list)
    for index, string in enumerate(s):
        dic[string].append(index)
    cycle = 0
    ind = -1
    for string in t:
        if dic[string] == []:
            print(-1)
            return
        elif dic[string][-1] <= ind:
            cycle += 1
            ind = dic[string][0]
        else:  # [2,6,7,10] 6の次は？
            ind = dic[string][bisect.bisect_right(
                dic[string], ind)]  # n以下の個数を数える
    print(cycle*len(s)+ind+1)


def __starting_point():
    main()
__starting_point()

def main():
    S = input()
    N = len(S)
    INF = N + 1
    T = input()
    # S で i 番目の何番目の後で文字 c が出てくるかを計算
    next_loc = [[INF for _ in range(N)] for _ in range(26)]
    for i, s in enumerate(S):
        c = ord(s) - ord('a')
        next_loc[c][i - 1] = 1
    for c in range(26):
        n = INF
        for i in range(N - 1, -(N + 1), -1):
            n = min(next_loc[c][i], n + 1)
            next_loc[c][i] = n
    # 答えを計算
    ans = 0
    index = -1
    for t in T:
        c = ord(t) - ord('a')
        i = next_loc[c][index]
        if i == INF:
            print(-1)
            return
        ans += i
        index = (index + i) % N
    print(ans)


def __starting_point():
    main()
__starting_point()

#!/usr/bin/env python3
 
import sys
# 以下を記述しないとTLEになる, 何故？
from heapq import heappush, heappop, heappushpop
from collections import defaultdict
# ---- ここまで -----------------------
 
input = sys.stdin.readline
 
S = input().rstrip()
T = input().rstrip()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return
 
ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1
 
print(ans)

def main():
    import sys
    import copy
    from bisect import bisect_right
    from collections import defaultdict
    input = sys.stdin.readline
    s, t = input().strip(), input().strip()
    lens = len(s)
    index_list = defaultdict(list)
    leng = defaultdict(int)
    for i, ss in enumerate(s):
        index_list[ss].append(i)

    for s, i in index_list.items():
        if i:
            leng[s] = len(index_list[s])

    prev = -1
    ans = 0
    for tt in t:
        if tt not in leng:
            print(-1)
            return False
        p = bisect_right(index_list[tt], prev)
        # print('tt={}, prev={}, p={}, ans={}'.format(tt, prev, p, ans))
        if p < leng[tt]:
            prev = index_list[tt][p]
        else:
            prev = index_list[tt][0]
            ans += lens

    print(ans+prev+1)

def __starting_point():
    main()
__starting_point()

def main():
    from functools import lru_cache
    import bisect
    S = input()
    T = input()
    if set(S) & set(T) != set(T):
        print((-1))
    else:
        lt = len(T)
        ls = len(S)
        st = set(T)
        D = dict()
        for t in st:
            D[t] = list()
            for i, s in enumerate(S):
                if t == s:
                    D[t].append(i)
        pre = -1
        cnt = 0

        @lru_cache(maxsize=None)
        def judge(pre, t):
            X = D[t]
            index = bisect.bisect(X, pre)
            if len(X) == index:
                return (X[0], True)
            else:
                return (X[index], False)

        for t in T:
            J = judge(pre, t)
            pre = J[0]
            if J[1]:
                cnt += 1

        print((cnt * len(S) + pre + 1))


def __starting_point():
    main()

__starting_point()

import sys
import math
import bisect
import heapq
import collections

S = input()
T = input()
lenS = len(S)
lenT = len(T)
F1 = [False]*26
F2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(lenS):
    F1[alpha.index(S[i])] = True
for i in range(lenT):
    F2[alpha.index(T[i])] = True
for i in range(26):
    if not F1[i] and F2[i]:
        print(-1)
        return

ind = S.index(T[0])
ans = ind+1
for i in range(1,lenT):
    S = S[ind+1:] + S[:ind+1]
    ind = S.index(T[i])
    ans += ind+1

print(ans)

import bisect

s = input()
t = input()

alphabet = [[] for _ in range(26)]
n = len(s)
s += s
for i in range(len(s)):
    alphabet[ord(s[i]) - ord("a")].append(i)
    
ans = 0
now = -1
for i in range(len(t)):
    t_i = ord(t[i]) - ord("a")
    j = bisect.bisect_right(alphabet[t_i], now)
    if j == len(alphabet[t_i]):
        print(-1)
        return
    else:
        now = alphabet[t_i][j]
        if now >= n:
            now -= n
            ans += n
            
print(ans + now + 1)

from collections import defaultdict
from bisect import bisect_right

s = input()
t = input()

n = len(s)

mp = [[] for _ in range(26)]
s += s
for i in range(len(s)):
    mp[ord(s[i]) - ord('a')].append(i)

ans = 0
now = -1
for i in range(len(t)):
    a = ord(t[i]) - ord('a')
    nxt = bisect_right(mp[a], now)
    if len(mp[a]) == nxt:
        print((-1))
        return

    now = mp[a][nxt]
    if now >= n:
        ans += n
        now -= n

print((ans + now + 1))