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):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math

    
    

    s = input().rstrip()
    ls = len(s)
    t = input().rstrip()
    lt = len(t)
    alphabet = 'abcdefghijklmnopqrstuvwxyz' 
    dic = {}
    for i in range(26):
        dic[alphabet[i]] = i
    moji = [[] for _ in range(26)]
    for i in range(ls):
        moji[dic[s[i]]].append(i+1)
    
    cnt = 0
    res = 0
    while cnt < lt:
        for i in range(cnt, lt):
            if not moji[dic[t[i]]]:
                print(-1)
                exit()
            if i == cnt:
                now = moji[dic[t[i]]][0] + 1
            else:
                nex = bisect_left(moji[dic[t[i]]], now)
                if nex == len(moji[dic[t[i]]]):
                    res += ls
                    cnt = i
                    break
                now = moji[dic[t[i]]][nex] + 1
        else:
            res += now - 1
            break
    print(res)

if __name__ == '__main__':
    main()

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math

    
    

    s = input().rstrip()
    ls = len(s)
    t = input().rstrip()
    lt = len(t)
    alphabet = 'abcdefghijklmnopqrstuvwxyz' 
    moji = [[] for _ in range(26)]
    for i in range(ls):
        idx = alphabet.index(s[i])
        moji[idx].append(i+1)
    
    cnt = 0
    res = 0
    while cnt < lt:
        for i in range(cnt, lt):
            idx = alphabet.index(t[i])
            if not moji[idx]:
                print(-1)
                exit()
            if i == cnt:
                now = moji[idx][0] + 1
            else:
                nex = bisect_left(moji[idx], now)
                if nex == len(moji[idx]):
                    res += ls
                    cnt = i
                    break
                now = moji[idx][nex] + 1
        else:
            res += now - 1
            break
    print(res)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
INF=10**18
def input():
    return sys.stdin.readline().rstrip()

def main():
    a=ord('a')
    s=list(map(lambda x:ord(x)-a,input()))
    N=len(s)
    t=list(map(lambda x:ord(x)-a,input()))
    l=[[-1]*26 for _ in range(len(s))]
    for i in range(N-1,-N,-1):
        for j in range(26):
            if s[i]==j:
                l[i-1][j]=i%N
            else:
                l[i-1][j]=l[i][j]
    ans=0
    index=N-1
    for a in t:
        n=l[index][a]
        if n==-1:
            print(-1)
            exit()
        if n>index:
            ans+=n-index
        else:
            ans+=n+N-index
        index=n
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
a = ord('a')

s = [ord(x)-a for x in list(input())]
t = [ord(x)-a for x in list(input())]

n = len(s)
m = len(t)

positions = [[0]*26 for i in range(n+1)]

for i in range(n):
    for j in range(26):
        if j == s[-1-i]:
            positions[-2-i][j] = n-i
        else:
            positions[-2-i][j] = positions[-1-i][j]

roop = 0
p = 0
flag = 1
for i in range(m):
    a = t[i]
    if positions[p][a]==0:
        roop += 1
        p = 0
    p = positions[p][a]
    if p == 0:
        flag = 0
        break

print(roop*n+p if flag else -1)

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

n = len(s)
m = len(t)

a = set(list(t))
b = set(list(s))

for x in a:
    if x not in b:
        print(-1)
        exit()

positions = [[0]*26 for i in range(n+1)]

for i in range(n):
    for j in range(26):
        if j == ord(s[-1-i])-97:
            positions[-2-i][j] = n-i
        else:
            positions[-2-i][j] = positions[-1-i][j]

roop = 0
p = 0
for i in range(m):
    a = ord(t[i])-97
    if positions[p][a]==0:
        roop += 1
        p = 0
    p = positions[p][a]

print(roop*n+p)

Solution (Python):
import sys
input = sys.stdin.readline
from collections import *
from bisect import *

s = input()[:-1]
t = input()[:-1]
idx = defaultdict(list)

for i in range(len(s)):
    idx[s[i]].append(i)

now = -1
cnt = 0

for i in range(len(t)):
    if t[i] not in idx:
        print(-1)
        exit()
        
    mark = bisect_right(idx[t[i]], now)
    
    if mark==len(idx[t[i]]):
        now = idx[t[i]][0]
        cnt += 1
    else:
        now = idx[t[i]][mark]
    
print(len(s)*cnt+now+1)

Solution (Python):
s = input()
t = input()
alpha = "abcdefghijklmnopqrstuvwxyz"
n = len(s)
m = len(t)
D = {}
E = {}
for i in range(n):
  if s[i] in D:
    D[s[i]][i] = i
  else:
    D[s[i]] = [-1 for _ in range(n)]
    D[s[i]][i] = i
  E[s[i]] = i
for i in D:
  p = E[i]
  for j in range(E[i], E[i] - n, -1):
    if D[i][(j+n)%n] == -1:
      D[i][(j+n)%n] = p
    else:
      p = j
x = 0
p = 0
for i in range(m):
  if t[i] in D:
    y = D[t[i]][p]
    if y < p:
      x += 1
    if i != m - 1:
      if y == n - 1:
        x += 1
        p = 0
      else:
        p = (y + 1) % n
    else:
      p = y
  else:
    x = -1
    break
if x == -1:
  print(x)
else:
  print(x*n+p+1)

Solution (Python):
from bisect import bisect_left

S = input()
T = input()
N = len(S)
NN = len(T)
S = [ord(S[i]) - 97 for i in range(N)]
T = [ord(T[i]) - 97 for i in range(NN)]

ind = [[] for _ in range(26)]
cnt = [0] * 26
for i in range(N):
    s = S[i]
    ind[s].append(i)
    cnt[s] += 1

part = 0
i = 0
j = -1
cond = 0
while i < NN:
    obj = T[i]
    if cnt[obj] == 0:
        cond = 1
        break

    tmp = bisect_left(ind[obj], j)
    if tmp == cnt[obj]:
        j = ind[obj][0]
        part += 1
        i += 1
        continue
    if ind[obj][tmp] == j:
        tmp += 1

    if tmp == cnt[obj]:
        j = ind[obj][0]
        part += 1
    else:
        j = ind[obj][tmp]

    i += 1


if cond:
    ans = -1
else:

    ans = N * part + (j + 1)

print(ans)

Solution (Python):
import bisect

s = input()
t = input()

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

count = [0,-1]

for i in range(len(t)):
    t1 = t[i]
    num = ord(t1) - ord('a')
    if not li[num]:
        print(-1)
        exit()
    else:
        if count[1] >= li[num][-1]:
            count[0] += 1
            count[1] = li[num][0]
        else:
            idx = bisect.bisect_right(li[num], count[1])
            count[1] = li[num][idx]

print(count[0] * len(s) + count[1] + 1)

Solution (Python):


from bisect import bisect_right

def main():
    s = input()
    t = input()
    indices = [[] for i in range(26)]
    n = len(s)
    for i in range(n):
        c = s[i]
        ic = ord(c) - ord("a")
        indices[ic].append(i)
    for i in range(26):
        if not indices[i]:
            continue
        indices[i].append(indices[i][0] + n)

    ptr = -1
    for c in t:
        ic = ord(c) - ord("a")
        if len(indices[ic]) == 0:
            print(-1)
            return
        nptr = bisect_right(indices[ic], ptr % n)
        ptr += indices[ic][nptr] - (ptr % n)

    print(ptr + 1)

if __name__ == "__main__":
    main()

Solution (Python):


from bisect import bisect_right

def main():
    s = input()
    t = input()
    indices = [[] for i in range(26)]
    n = len(s)
    for i in range(n):
        c = s[i]
        ic = ord(c) - ord("a")
        indices[ic].append(i)
    for i in range(26):
        if not indices[i]:
            continue
        indices[i].append(indices[i][0] + n)

    ptr = -1
    for c in t:
        ic = ord(c) - ord("a")
        if len(indices[ic]) == 0:
            print(-1)
            return
        nptr = bisect_right(indices[ic], ptr % n)
        ptr += indices[ic][nptr] - (ptr % n)

    print(ptr + 1)

if __name__ == "__main__":
    main()

Solution (Python):
from sys import exit

s = input()
t = input()

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
alph_list = dict()
for i in range(26):
  alph_list[alphabet[i]] = i

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

for i in range(len(s)):
  key = s[i]
  counter[alph_list[key]].append(i)

ans = 0
ans_mod = 0
flag = True
for i in range(len(t)):
  key = alph_list[t[i]]
  if not counter[key]:
    flag = False
    break
  l, r = 0, len(counter[key])
  while r-l > 1:
    bit = (r+l)//2
    if counter[key][bit] >= ans:
      r = bit
    else:
      l = bit
  if r == len(counter[key]) and counter[key][l] < ans:
    ans_mod += 1
    ans = counter[key][0]+1
  elif l == 0 and counter[key][l] >= ans:
    ans = counter[key][l]+1
  else:
    ans = counter[key][r]+1
if flag:
  print(ans_mod*len(s)+ans)
else:
  print(-1)

Solution (Python):
import bisect

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

    indexes = dict()

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

    point =-1
    roops = 0
    for i in T:
        if not i in indexes:
            print(-1)
            return
        
        nxt = bisect.bisect_right(indexes[i],point)

        if nxt == len(indexes[i]):
            roops += 1
            point = indexes[i][0]
        else:
            point = indexes[i][nxt]


    print(len(S)*roops+point + 1)





resolve()

Solution (Python):


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

def srch(num,li):
    if len(li)==0:
        return -10

    fst = 0
    lst = len(li)-1
    while(lst>fst):
        mid = (fst+lst)//2
        if li[mid] <= num:
            fst = mid+1
        else:
            lst = mid
    return li[fst]

def main():
    N = len(S)
    li = [[] for _ in range(26)]
    for i in range(N):
        mm = ord(S[i])-97
        li[mm].append(i)
    for i in range(26):
        if len(li[i])>0:
            li[i].append(li[i][0]+N)
    
    cnt1 = 0
    cnt2 = -1
    for i in range(len(T)):
        mm = ord(T[i])-97
        cnt2 = srch(cnt2,li[mm])
        if cnt2 == -10:
            print(-1)
            return

        if cnt2>=N:
            cnt2 %= N
            cnt1 += 1
    print(cnt1*N+cnt2+1)


    

    
        

if __name__ == '__main__':
    main()

Solution (Python):
def make_tree(n):
    i = 2
    while True:
        if i >= n * 2:
            tree = [[inf] * i for _ in range(26)]
            break
        else:
            i *= 2
    return tree

def update(i, x, tree):
    i += len(tree) // 2
    tree[i] = x
    i //= 2
    while True:
        if i == 0:
            break
        tree[i] = min(tree[2 * i], tree[2 * i + 1])
        i //= 2
    return

def find(s, t, tree):
    s += len(tree) // 2
    t += len(tree) // 2
    ans = inf
    while True:
        if s > t:
            break
        if s % 2 == 0:
            s //= 2
        else:
            ans = min(ans, tree[s])
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            ans = min(ans, tree[t])
            t = (t - 1) // 2
    return ans

s = list(input())
t = list(input())
inf = 10 ** 6
n = len(s)
first = [-2] * 26
tree = make_tree(n)
for i in range(n):
    m = ord(s[i]) - 97
    update(i, i, tree[m])
    if first[m] == -2:
        first[m] = i
ans = 1
c = -1
for i in t:
    m = ord(i) - 97
    if not c == -1:
        u = -1
        u = find(c + 1, n - 1, tree[m])
        if u == -1 or u == inf:
            ans += n
            c = -1
        else:
            c = u
    if c == -1:
        c = first[m]
        if c == -2:
            print(-1)
            exit()
ans += c
print(ans)

Solution (Python):
def make_tree(n):
    i = 2
    while True:
        if i >= n * 2:
            tree = [[inf] * i for _ in range(26)]
            break
        else:
            i *= 2
    return tree

def update(i, x, tree):
    i += len(tree) // 2
    tree[i] = x
    i //= 2
    while True:
        if i == 0:
            break
        tree[i] = min(tree[2 * i], tree[2 * i + 1])
        i //= 2
    return

def find(s, t, tree):
    s += len(tree) // 2
    t += len(tree) // 2
    ans = inf
    while True:
        if s > t:
            break
        if s % 2 == 0:
            s //= 2
        else:
            ans = min(ans, tree[s])
            s = (s + 1) // 2
        if t % 2 == 1:
            t //= 2
        else:
            ans = min(ans, tree[t])
            t = (t - 1) // 2
    return ans

s = list(input())
t = list(input())
inf = 10 ** 6
n = len(s)
first = [-2] * 26
tree = make_tree(n)
for i in range(n):
    m = ord(s[i]) - 97
    update(i, i, tree[m])
    if first[m] == -2:
        first[m] = i
ans = 1
c = -1
for i in t:
    m = ord(i) - 97
    if not c == -1:
        u = -1
        u = find(c + 1, n - 1, tree[m])
        if u == -1 or u == inf:
            ans += n
            c = -1
        else:
            c = u
    if c == -1:
        c = first[m]
        if c == -2:
            print(-1)
            exit()
ans += c
print(ans)

Solution (Python):

"""
sの好きなだけのループに対する部分文字列tを求める
tにあってsにない文字がある時点でno
そうでないならば必ず達成可能で、
tに対してループを回し(i)、
sのj文字目に関して、それより後に初めて出てくるt[i+1]の場所をindexで返し,i+=1,j=そのindex
にする。
そのようなindexがないならば、j=0とし、またはじめから回す。
"""
import sys
import bisect
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

s = readline().rstrip().decode('utf-8')
t = readline().rstrip().decode('utf-8')
s_s = set(list(s))
t_s = set(list(t))
flag = 1 if s_s & t_s == t_s else 0

if not flag:
    print(-1)
    exit()


lst1 = [[] for _ in range(26)]
kijun = ord("a")
for idx,i in enumerate(s):
    lst1[ord(i)-kijun].append(idx)

i = 0
roop = 0
count = 0
while True:
    if i >= len(t):
        print(roop*len(s)+count)
        break
    now = ord(t[i])-kijun
    res = bisect.bisect_left(lst1[now],count)
    if res == len(lst1[now]):
        roop += 1
        count = 0
        res = bisect.bisect_left(lst1[now],count)
        count = lst1[now][res]+1 
    else:
        count = lst1[now][res]+1
    i += 1

Solution (Python):

"""
sの好きなだけのループに対する部分文字列tを求める
tにあってsにない文字がある時点でno
そうでないならば必ず達成可能で、
tに対してループを回し(i)、
sのj文字目に関して、それより後に初めて出てくるt[i+1]の場所をindexで返し,i+=1,j=そのindex
にする。
そのようなindexがないならば、j=0とし、またはじめから回す。
"""
import sys
import bisect
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

s = readline().rstrip().decode('utf-8')
t = readline().rstrip().decode('utf-8')
s_s = set(list(s))
t_s = set(list(t))
flag = 1 if s_s & t_s == t_s else 0

if not flag:
    print(-1)
    exit()


lst1 = [[] for _ in range(26)]
kijun = ord("a")
for idx,i in enumerate(s):
    lst1[ord(i)-kijun].append(idx)

i = 0
roop = 0
count = 0
while True:
    if i >= len(t):
        print(roop*len(s)+count) 
        break
    now = ord(t[i])-kijun
    res = bisect.bisect_left(lst1[now],count)
    if res == len(lst1[now]):
        roop += 1
        count = 0
        res = bisect.bisect_left(lst1[now],count)
        count = lst1[now][res]+1 
    else:
        count = lst1[now][res]+1
    i += 1

Solution (Python):
s=input()
t=input()
lens=len(s)
lent=len(t)

alp="abcdefghijklmnopqrstuvwxyz"

D={c : {i:-1 for i in range(lens*2)} for c in alp}

tab={c:0 for c in alp}

for i in range(lens*2):
    nowc=s[i%lens]
    for q in range(tab[nowc],i+1):
        D[nowc][q]=i
    tab[nowc]=i+1

ans=0
pos=0
for i in range(lent):
    nowc=t[i]
    if D[nowc][pos]==-1:
        print(-1)
        break
    ans+=D[nowc][pos]-pos+1
    
    pos=D[nowc][pos]+1
    pos%=lens
else:
    print(ans)

Solution (Python):
import bisect

s = input()
t = input()
p = {}
for i in range(len(s)):
    c = s[i]
    if c not in p:
        p[c] = []
    p[c].append(i)

over = 0
ret = 0
for c in t:
    if c not in p:
        print(-1)
        exit(0)
    ind = bisect.bisect_left(p[c], ret)
    if ind < len(p[c]):
        ret = p[c][ind] + 1
    else:
        ret = p[c][0] + 1
        over += 1

print(over * len(s) + ret)

Solution (Python):
import bisect

s = input()
t = input()
p = {}
for i in range(len(s)):
    c = s[i]
    if c not in p:
        p[c] = []
    p[c].append(i)

over = 0
ret = 0
for c in t:
    if c not in p:
        print(-1)
        exit(0)
    ind = bisect.bisect_left(p[c], ret)
    if ind < len(p[c]):
        ret = p[c][ind] + 1
    else:
        ret = p[c][0] + 1
        over += 1

print(over * len(s) + ret)

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

import bisect
point_dic = {}
for i in range(26):
    alp = chr( ord('a') + i )
    point_dic[alp] = []

for i in range(len_s):
    i_alp = s[i]
    point_dic[i_alp].append(i+1)

now = 1
cycle = 0
for i in t:
    points = point_dic[i]
    if(len(points) == 0):
        print(-1)
        exit()
    tmp = bisect.bisect_left(points, now)
    if(tmp == len(points)):
        now = points[0]+1
        cycle += 1
    else:
        now = points[tmp]+1

ans = cycle * len_s + now - 1
print(ans)

Solution (Python):
import bisect
S=list(input())
T=list(input())
A=[[] for i in range(26)]
for i in range(len(S)):
  A[ord(S[i])-97].append(i+1)
a=0
b=0
for i in range(len(T)):
  k=ord(T[i])-97
  if len(A[k])==0:
    print(-1)
    exit()
  if b>=A[k][-1]:
    a=a+1
    b=A[k][0]
    continue
  else:
    b=A[k][bisect.bisect_right(A[k],b,lo=0,hi=len(A[k]))]
print(a*len(S)+b)

Solution (Python):


def submit():
    s = input()
    t = input()
    char_set = set(s)
    next_char = {c: -1 for c in char_set}
    char_list = {(c, len(s)): -1 for c in char_set}

    for i in reversed(range(len(s))):
        for c in char_set:
            if c == s[i]:
                char_list[(c, i)] = i
            else:
                char_list[(c, i)] = char_list[(c, i + 1)]
            
    loop = 0
    curr = 0
    for c in t:
        
        if c not in char_set:
            print(-1)
            return
        if char_list[(c, curr)] < 0:
            loop += 1
            curr = 0
        curr = char_list[(c, curr)] + 1
    print(loop * len(s) + curr)
        

submit()

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

NS = len(S)
NT = len(T)
alp = {}
for i in range(26):
    alp[chr(97+i)] = i
D = [[] for i in range(26)]
for i in range(NS):
    D[alp[S[i]]].append(i)
inf = float("inf")
for i in range(26):D[i].append(inf)
k = 0
l = -1
ans = -1
for i in range(NT):
    index = alp[T[i]]
    if D[index] == [inf]:break
    b = bisect(D[index],l)
    if D[index][b]==inf:
        k += 1
        l = D[index][0]
    else:
        l = D[index][b]
    if i==NT-1:ans = k*NS+l+1
print(ans)

Solution (Python):
import bisect
w1=input()
w2=input()
d={}
for i in list("qwertyuiopasdfghjklzxcvbnm"):
  d[i]=[]
for i in range(len(w1)):
  d[w1[i]].append(i+1)
num=len(w1)
for i in w2:
  if d[i]==[]:
    print(-1)
    exit()
now=0
count=0
num2=len(w2)
for i in range(num2):
  d1=d[w2[i]]
  if d1[-1]<now:
    now=d1[0]+1
    count+=1
  else:
    index=bisect.bisect_left(d1,now)
    now=d1[index]+1
print(count*num+now-1)

Solution (Python):
s = input()
t = input()
ans = 0
cur = 0
cnt = 0
for i in t:
  f = s.find(i, cur)
  if f == -1:
    cnt += 1
    f = s.find(i)
    if f == -1:
      print(-1)
      exit()
    else:
      cur = f + 1
  else:
    cur = f + 1
print(cur + len(s) * cnt)

Solution (Python):
s = input()
t = input()
counter = 0
idx = -1
if set(t) <= set(s):
  for i in range(len(t)):
    idx = s.find(t[i],idx+1)
    if idx == -1:
      counter += 1
      idx = s.find(t[i],idx+1)
  print(counter * len(s) +idx +1)
else:
  print(-1)

Solution (Python):
s = input()
t = input()
len_s = len(s)
a = ord('a')
dictionary = {chr(a + i): [[], 0] for i in range(26)}
for i in range(len_s):
  dictionary[s[i]][0].append(i)
  dictionary[s[i]][1] += 1
repeat = 0
cur_index = -1
for c in t:
  indices, len_indices = dictionary[c]
  if len_indices == 0:
    repeat = 0
    cur_index = -2
    break
  inf = -1
  sup = len_indices
  while sup - inf > 1:
    x = (inf + sup) // 2
    if indices[x] > cur_index:
      sup = x
    else:
      inf = x
  if sup == len_indices:
    repeat += 1
    cur_index = indices[0]
  else:
    cur_index = indices[sup]
print(len_s * repeat + cur_index + 1)

Solution (Python):
from bisect import *
s = input()
t = input()
pos = {}
for j,i in enumerate(s):
  if i in pos.keys():
  	pos[i].append(j+1)
  else:
    pos[i] = [j+1]
n = len(s)
for i in pos.keys():
  pos[i].append(pos[i][0] + n)
ans = 0
last = 0
for i in t:
  if not i in s:
    print(-1)
    exit()
  last = pos[i][bisect(pos[i],last)]
  if last > n:
    last -= n
    ans += n
print(ans + last)

Solution (Python):
mod = 10 ** 9 + 7
mod2 = 2**61+1
from collections import deque
import heapq
from bisect import bisect_left, insort_left

def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def main():
    r = solve()
    print(r)

def solve():
    s = input()
    s = [ord(i) - ord("a") for i in s]
    N = len(s)
    t = input()
    t = [ord(i) - ord("a") for i in t]

    posit = {}
    for i in range(0, ord("z")-ord("a")+1):
        posit[i] = []

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

    ans = 0
    cur = -1
    for src_target in t:
        if not posit[src_target]:
            return -1
        if posit[src_target][-1] <= cur: 
            ans += (N-cur-1)
            cur = -1
            

        idx = bisect_left(posit[src_target], cur+1) 
        next = posit[src_target][idx]
        ans += next - cur
        cur = next
        

    return ans





def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p, mod_= mod):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

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

ans1=0
ans2=0

ss=s*2

for i in range(len(t)):
    a=ss.find(t[i],ans2)
    if a==-1:
        ans=-1
        break
    if a>=len(s):
        ans1+=1
    ans2=a%(len(s))+1
    ans=ans1*len(s)+ans2
print(ans)

Solution (Python):
import bisect
s = list(input())
t = list(input())
ls = len(s)
check = [[] for i in range(26)]
for i in range(len(s)):
    o = ord(s[i])-ord("a")

    check[o].append(i+1)
ans = 0
c1 = 0

for i in t:
    o =ord(i)-ord("a")
    if check[o]:
        x = bisect.bisect_right(check[o],ans) 
        if x == len(check[o]):
            c1 += 1
            ans = check[o][0]
        else:
            ans = check[o][x]
            

    else:
        print(-1)
        exit()
 
print(ans+c1*ls)

Solution (Python):
sl = list(input())
tl = list(input())
n = len(sl)
from collections import defaultdict
dic = defaultdict(list)

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

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

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

print(ans)

Solution (Python):
s = list(input())
t = list(input())
l = len(s)
sl = [[] for _ in range(26)]
for i in range(l):
	j = ord(s[i])-97
	sl[j].append(i)
sord = [[-1 for _ in range(l)] for _ in range(26)]
checksord = [0 for _ in range(26)]
for i in range(26):
	for j in range(len(sl[i])):
		cnt = sl[i][j]
		for q in range(checksord[i], cnt):
			sord[i][q] = cnt
		checksord[i] = cnt

for i in range(26):
	for j in range(l):
		if (sl[i] != []) & (sord[i][j] == -1):
			sord[i][j] = sl[i][0] + l



j = ord(t[0])-97
if sl[j] == []:
	ans = -1
else: 
	ans = sl[j][0]

if ans != -1:
	for i in range(1, len(t)):
		j = ord(t[i])-97
		if sl[j] == []:
			ans = -1
			break
		else:
			w = ans % l
			ans = ans - w + sord[j][w]
			

if ans == -1:
	print(ans)
else:
	print(ans+1)

Solution (Python):
import sys
s=input()
ss=s+s
t=input()
l=len(s)
d={}
for i in range(26):
    d[chr(ord("a")+i)]=i
ref=[[] for _ in range(26)]
for i in range(2*l):
    ref[d[ss[i]]].append(i)

for i in range(26):
    if ref[i]==[]: ref[i].append(-1)

tmp=[0 for i in range(26)]
next=[[-1]*26 for i in range(l)]
for i in range(l):
    tmp[d[s[i]]]+=1
    for j in range(26):
        next[i][j]=ref[j][tmp[j]]

p=s.find(t[0])
if p==-1: print(-1);sys.exit()
ans=p

for i in range(1,len(t)):
    x=d[t[i]]
    q=next[p][x]
    if q==-1: print(-1);sys.exit()
    ans+=-p+q
    p=q%l
print(ans+1)

Solution (Python):
import sys
s=input()
t=input()
l=len(s)
d={}
for i in range(26):
    d[chr(ord("a")+i)]=i
ref=[[] for _ in range(26)]
for i in range(l):
    ref[d[s[i]]].append(i)

for i in range(26):
    if ref[i]==[]: ref[i].append(-1)

tmp=[0 for i in range(26)]
next=[[-1]*26 for i in range(l)]
for i in range(l):
    x=d[s[i]]
    tmp[x]=(tmp[x]+1)%len(ref[x])
    for j in range(26):
        next[i][j]=ref[j][tmp[j]]

p=s.find(t[0])
ans=p

if p==-1: print(-1);sys.exit()
for i in range(1,len(t)):
    x=d[t[i]]
    q=next[p][x]
    if q==-1: print(-1);sys.exit()
    ans+=-p+q
    if p>=q: ans+=l
    p=q
print(ans+1)

Solution (Python):
S = input()
T = input()
dic = {}
for i,s in enumerate(S):
  if s not in dic:
    dic[s] = [i]
  else:
    dic[s].append(i)

ind = -1
loop = 0
import bisect
for t in T:
  if t not in dic:
    ans = -1
    break
  if dic[t][-1]<=ind:
    loop += 1
    ind = dic[t][0]
  else:
    i = bisect.bisect_right(dic[t],ind)
    ind = dic[t][i]
  

else:
  ans = len(S)*loop+ind+1
          
print(ans)

Solution (Python):
S = input()
T = input()
dic = {}
for i,s in enumerate(S):
  if s not in dic:
    dic[s] = [i]
  else:
    dic[s].append(i)

ind = -1
loop = 0
import bisect
for t in T:
  if t not in dic:
    ans = -1
    break
  if dic[t][-1]<=ind:
    loop += 1
    ind = dic[t][0]
  else:
    i = bisect.bisect_right(dic[t],ind)
    ind = dic[t][i]
  

else:
  ans = len(S)*loop+ind+1
          
print(ans)

Solution (Python):


























from bisect import bisect_left

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

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

for i in range(n):
    index_list[ord(s[i]) - ord('a')].append(i)
for i in range(n):
    index_list[ord(s[i]) - ord('a')].append(i+n)

p = 0  
ans = 0
for j in range(m):
    ch = ord(t[j]) - ord('a')
    if len(index_list[ch]) == 0:
        
        print(-1)
        exit()
    next_pos = bisect_left(index_list[ch], p)
    p = index_list[ch][next_pos] + 1
    if p >= n:
        p -= n
        ans += n
    

ans += p
print(ans)

Solution (Python):
import bisect
import sys
sys.setrecursionlimit(10 ** 7)

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

LS = len(S)
LT = len(T)

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

for i in range(LS):
    n = ord(S[i]) - 97
    POS[n].append(i)


cnt = 0
prev = -1
for i in range(LT):
    n = ord(T[i]) - 97

    if not POS[n]:
        print(-1)
        exit()

    ps = POS[n]
    p = bisect.bisect_right(ps, prev)

    if p == len(ps):
        cnt += 1
        p = bisect.bisect_right(ps, -1)

    prev = ps[p]


ans = cnt * LS + prev + 1
print(ans)

Solution (Python):
import sys

import bisect

from collections import Counter, deque, defaultdict











readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


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

    sd = defaultdict(list)

    sl = len(s)

    for i in range(sl):
        c = s[i]
        sd[c].append(i+1)

    tl = len(t)
    prev = 0

    ans = 0

    for i in range(tl):
        c2 = t[i]
        appear = sd[c2]
        if len(appear) == 0:
            print(-1)
            sys.exit()

        appear_max = appear[-1]
        if appear_max <= prev:
            nxt = appear[0]
        else:
            nxt = appear[bisect.bisect_right(appear, prev)]
        forward = nxt - prev
        if forward <= 0:
            forward += sl
        ans += forward
        prev = nxt

    print(ans)


if __name__ == '__main__':
    main()