Problem:


Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.



Sample input:
contest
son


Sample output:
10

Submission status: Wrong Answer

Solution code:
s=list(input())
t=list(input())
x=0
y=0
ans=0

for i in range(len(s)):
    s[i]=list(s[i])
    s[i].append(i)
for i in range(len(t)):
    t[i]=list(t[i])
    t[i].append(i)
s1=sorted(s)
t1=sorted(t)
dp=[0]*len(t)


for i in range(len(t)):
    for j in range(x,len(s)):
        if t1[i][0]==s1[j][0]:
            dp[t1[i][1]]=s1[j][1]
            x=j
            break
        if j==len(s)-1:
            print('-1')
            exit()

ans=dp[0]+1
for i in range(1,len(t)):
    if dp[i]<=dp[i-1]:
        ans+=len(s)-dp[i-1]+dp[i]
    else:
        ans+=dp[i]-dp[i-1]
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

check = 0
for i in t:
    if i in s:
        check += 1
if check != len(t):
    print(-1)
    exit()
count = 0
while(True):
    for i in s:
        count += 1
        for a in t:
            if a in i:
                t = t.lstrip(a)
                break
        if t == '':
            print(count)
            exit()

Submission status: Wrong Answer

Solution code:
words = lambda t : list(map(t, input().split()))
s = input()
t = input()

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

for k,v in dict.items():
    dict[k] = sorted(v)

#print(dict)

from bisect import bisect_right
def find_min_t(cur, c):
    if c not in dict:
        return -1
    k = bisect_right(dict[c], cur)
    if k >= len(dict[c]):
        return dict[c][0]
    else:
        return dict[c][k]

cur = 0
ans = 0
succeed = True
for c in t:
    i = find_min_t(cur, c)
    #print(c, i, cur)
    if i == -1:
        succeed = False
        break
    if i < cur:
        ans += len(s)
    cur = i

if succeed:
    print(ans + cur + 1)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
s=list(input())
t=list(input())
x=0
y=0
ans=0

for i in range(len(s)):
    s[i]=list(s[i])
    s[i].append(i)
for i in range(len(t)):
    t[i]=list(t[i])
    t[i].append(i)
s1=sorted(s)
t1=sorted(t)
dp=[0]*len(t)


for i in range(len(t)):
    for j in range(x,len(s)):
        if t1[i][0]==s1[j][0]:
            dp[t1[i][1]]=s1[j][1]
            x=j
            break
        if j==len(s)-1:
            print('-1')
            exit()

ans=dp[0]+1
for i in range(1,len(t)):
    print(ans)
    if dp[i]<=dp[i-1]:
        ans+=len(s)-dp[i-1]+dp[i]
    else:
        ans+=dp[i]-dp[i-1]
print(ans)

Submission status: Wrong Answer

Solution code:
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; cnt = 0; ansli = []; tmpli = []; candili = []; stillset = set()
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]#WideIntPoint
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def s_list(): return list(input())
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]#HeightString
def mi(n): return [wi() for _ in range(n)]#MatrixInt
def num__grid(n): return [[int(i) for i in sys.stdin.readline().split()[0]] for _ in range(n)]#NumberGrid
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]
def grid(n): return [s_list() for _ in range(n)]


s = input()
t = input()
ns = len(s)
nt = len(t)
alpha = "abcdefghijklmnopqrstuvwxyz"
aldi = {}
for i in alpha:
    aldi[i] = []

for i in range(ns):
    aldi[s[i]].append(i + 1)


num = []
if aldi[t[0]] == []:
    print(-1)
    exit()
mae = aldi[t[0]][0]
num.append(mae)
for i in range(1, nt):
    if aldi[t[i]] == []:
        print(-1)
        exit()
    else:
        kk = bisect_right(aldi[t[i]], mae)
        if kk == len(aldi[t[i]]):
            kk = aldi[t[i]][0]
        else:
            kk = aldi[t[i]][kk]
        mae = kk
        num.append(kk)

ans += num[0]
for i in range(1, len(num)):
    if num[i] < num[i - 1]:
        ans += ns - num[i - 1] + num[i]
    else:
        ans += num[i] - num[i - 1]

print(ans)

Submission status: Wrong Answer

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

S = list(s)

C = [[]for i in range(26)]
for i in range(len(S)):
    C[ord(S[i])-97].append(i+1)

idx = 0
ans = 0
l = len(s)
for i in range(len(t)):
    now = ord(t[i])-97
    if C[now] == []:
        ans = -1
        break
    up = bisect.bisect_right(C[now], idx)
    if up >= len(C[now]):
        up = bisect.bisect_right(C[now], 0)
        ans += C[now][up-1] + l-idx
        idx = C[now][up-1]
    else:
        ans += C[now][up] - idx
        idx = C[now][up]

print(ans)

Submission status: Wrong Answer

Solution code:
def check(t,s):
    i=0
    for j in range(len(s)):
        if(i==len(t)):
            return (True,j)
        if(t[i]==s[j]):
            i+=1
    if(i==len(t)):
        return (True,len(s))
    return False,-1
        

def solve(s,t):
    new_s = s
    for a in t:
        if a not in s:
            return -1
    l = 1
    r = 1000
    final = 10**100
    while(l<=r):
        mid = (l+r)//2
        new_s = s*mid
        done,ans = check(t,new_s)
        if(done):
            final = min(final,ans)
            r = mid-1
        else:
            l = mid+1
    return final

s = input()
t = input()
print(solve(s,t))

Submission status: Wrong Answer

Solution code:
import sys

s = input()
t = input()

a = []
ls = len(s)
lt = len(t)

for i in t:
    try:
        a.append(s.index(i))
    except:
        print("-1")
        sys.exit()

p = 0
q = 0

for i in range(lt):
    if i > 0:
        if i == lt - 1:
            q = a[i]
            if a[i - 1] > a[i]:
                p += 1
        else:
            if a[i - 1] > a[i]:
                p += 1
            else:
                q = a[i]
    else:
        q = a[i]

ans = p * ls + q + 1

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_left

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


    print('-1')
    return

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

    posS = defaultdict(list)

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

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

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

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

    print(ans)

sol()

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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

flag = True
a_list = []
for i in range(len(t)):
    a = s.find(t[i])
    if a == -1:
        flag = False
        break
    else:
        a_list.append(a)

if flag:
    cnt = 0
    for i in range(len(a_list)-1):
        if a_list[i] >= a_list[i+1]:
            cnt += 1
    print(cnt*len(s) + a_list[-1] + 1)
else:
    print(-1)

Submission status: Wrong Answer

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

N = len(s)

tN = len(t)

o_a = ord("a")
o_z = ord("z")

def alpha_index(c):
    return ord(c) - ord("a")

# 次の特定の文字が何文字先にあるか
next_string = [[-1 for _ in range(26)] for _ in range(len(s))]

for i in range(N * 2 + 2, -1, -1):
    for byte_c in range(26):
        if s[(i + 1) % N] == chr(o_a + byte_c):
            next_string[i % N][byte_c] = 1
        elif next_string[i % N][byte_c] == -1 and next_string[(i + 1) % N][byte_c] > 0:
            next_string[i % N][byte_c] = next_string[(i + 1) % N][byte_c] + 1

ans = next_string[N - 1][alpha_index(t[0])]

if ans == -1:
    print(-1)
    exit()

for i in range(1, tN):
    nextindex = next_string[ans % N][alpha_index(t[i])]
    if nextindex == -1:
        print(-1)
        exit()
    ans += nextindex

print(ans + 1)

Submission status: Wrong Answer

Solution code:
s,t = open(0).read().split()

cannot = False
for i in range(len(t)):
  if s.count(t[i]) == 0:
    cannot = True

mojisu = 0

nokori = ""

if cannot:
  print(-1)
else:
  for i in range(len(t)):

    #print(t[i],nokori)
    if nokori.count(t[i]) == 0:
      nokori = nokori + s  

    si = nokori.index(t[i])
  
    mojisu+=si

    #print(nokori)
    nokori = nokori[si:]
  
  print(mojisu+1)

Submission status: Wrong Answer

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

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

inds = defaultdict(list)
inds_cnt = defaultdict(int)

for i in range(len(s)):
    inds[s[i]].append(i)
for i in range(97,97+26):
    inds_cnt[chr(i)] = len(inds[chr(i)])

k = 0
ans = 0
N = len(s)

for c in t:
    j = bisect(inds[c],k)
    if j == inds_cnt[c]:
        k = inds[c][0]
        ans+=N
    else:
        k=inds[c][j]
print(ans+k+1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import bisect
from collections import defaultdict

S=input()
T=input()

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


    result=1
    mx=-1
    for t in T:
        flag=True

        if not obj[t]:
            return -1
        
        pos=(obj[t]+[-1])[bisect.bisect_right(obj[t],mx)]
        if not pos+1:
            mx=obj[t][0]
            result+=1
        else:
            mx=pos
    
    return len(S)*(result-1)+pos+1
print(solve())

Submission status: Wrong Answer

Solution code:
import bisect

s = input()
t = input()

s_dict = {}
for i, si in enumerate(s):
    s_dict[si] = [i] if si not in s_dict else s_dict[si] + [i]

s_len = len(s)
counter = 0
fail = False
for ti in t:
    if ti not in s_dict:
        fail = True
        break
    # counter in s
    c_in_s = counter % s_len
    c = bisect.bisect_left(s_dict[ti], c_in_s)
    if c == len(s_dict[ti]):
        counter += s_len - c_in_s
        counter += s_dict[ti][0]
    else:
        counter += s_dict[ti][c] - c_in_s

print(counter + 1 if not fail else '-1')

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
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 LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

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

  ln=len(s)

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

  for x in b:
    if x not in a:
      return -1

  q=['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']
  r=[[] for _ in range(len(q))]

  for i,x in enumerate(s):
    r[q.index(x)].append(i)

  ans=1
  i=0
  for x in t:
    if i>=len(s):
      i=0
    _l=r[q.index(x)]
    a=bisect.bisect_right(_l,i)
    __i=_l[a-1]
    if a==0:
      _i=_l[0]
    else:
      _i=__i
    # print(i,_l)
    if _i<i:
      ans+=ln-i-1
      ans+=_i+1
    else:
      ans+=_i-i
    i=_i
    # print(ans)

  return ans

# main()
print(main())

Submission status: Wrong Answer

Solution code:
def main():
    s = input()
    t = input()
    s_set = set(list(s))
    s_dict = {}
    s_len = len(s)
    t_list = list(t)
    t_set = set(t_list)
    c = 0
    ans = []
    ans_append = ans.append
    for i in s_set:
        s_dict[i] = []
    for i in range(s_len):
        s_dict[s[i]].append(i)
    if len(t_set) == len(t_set & s_set):
        for i in t_list:
            idxs = s_dict[i]
            if idxs[-1] <= c:
                c = idxs[0]
                ans_append(c)
            else:
                for idx in idxs:
                    if idx > c:
                        c = idx
                        ans_append(c)
                        break
        count = 0
        for i in range(len(ans)-1):
            if ans[i] >= ans[i+1]:
                count += 1
        print(s_len*count + ans[-1] + 1)
    else:
        print(-1)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

possible = True
dt = defaultdict(int)
for i in range(len(t)):
    dt[t[i]] += 1
    if t[i] not in ds:
        possible = False


if possible:
    n = len(s)
    m = len(dt)
    edge = []
    for i in range(n):
        if s[i] in dt:
            edge.append((s[i], i, {}))


    x = 0
    for i in range(len(edge)):
        if edge[i][0] == t[0]:
            x = i

        for j in range(1, len(edge)+1):
            k = (i + j) % len(edge)
            if edge[k][0] not in edge[i][2]:
                if i == k:
                    edge[i][2][ edge[k][0] ] = (n, k)
                else:
                    edge[i][2][ edge[k][0] ] = ((edge[k][1] - edge[i][1] + n) % n, k)
            if len(edge[i][2]) == m:
                break

    # for i in range(len(edge)):
    #     print(edge[i])

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

    for i in range(1, len(t)):
        a, b = edge[x][2][t[i]]
        ans += a
        x = b
else:
    ans = -1

print(ans)

Submission status: Wrong Answer

Solution code:
S=input()
T=input()
import numpy as np
dp=np.ones((26,len(S)),dtype=np.int64)*(10**6)
for i in range(len(S)-1,-1,-1):
    dp[ord(S[i])-ord('a'),i]=0
    dp[:,i-1]=np.min((dp[:,i-1],dp[:,i]+1),axis=0)
for i in range(len(S)-1,-1,-1):
    dp[:,i-1]=np.min((dp[:,i-1],dp[:,i]+1),axis=0)
x=1
i=0
for t in T:
    ti=ord(t)-ord('a')
    if dp[ti,i]<1e6:
        x+=dp[ti,i]
        i=(i+dp[ti,i])%len(S)
    else:
        x=-1
        break
print(int(x))

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
def main():
    from collections import defaultdict
    import sys
    
    s = input()
    t = input()
    ds = defaultdict(int)
    di = {}
    
    cha = [chr(i) for i in range(97, 97+26)]
    for i in cha:
        di[i] = defaultdict(int)
    for a in s:
        ds[a] = 1
        
    flag = 0
    for b in t:
        if ds[b] == 0:
            flag = 1
    if flag == 1:
        print(-1)
        sys.exit()

    s2 = s[::-1]
    for i in range(2*len(s)):
        for j in di[s2[(i-1)%len(s)]]:
            di[s2[i%len(s)]][j] = di[s2[(i-1)%len(s)]][j] + 1
        di[s2[i%len(s)]][s2[i%len(s)]] = 0
    tmp = t[0]
    for k in range(len(s)):
        if tmp == s[k]:
            answer = k+1
            break
    for k in range(len(t)-1):
        l = k+1
        answer += di[tmp][t[l]]
        tmp = t[l]
    print(answer)
      

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

from bisect import bisect_right as br

def main():
    S = [s for s in input()]
    T = [t for t in input()]
    slen = len(S)
    tlen = len(T)

    dic = {}
    for i in range(slen):
        if S[i] in dic:
            dic[S[i]].append(i)
        else:
            dic[S[i]] = [i]

    ans = 0
    pre = 0
    for j in range(tlen):
        t = T[j]
        if t in dic:
            point = br(dic[t],pre)
            if point == len(dic[t]):
                ans += slen - pre + dic[t][0]
                pre = dic[t][0]
            else:
                if pre == dic[t] == point:
                    ans += slen
                else:
                    ans += dic[t][point] - pre
                    pre = dic[t][point]
        else:
            print(-1)
            return
    print(ans + 1)
    return 
main()

Submission status: Wrong Answer

Solution code:
from bisect import *

S = input()
T = input()

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

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

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

Submission status: Wrong Answer

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

for i in list(t):
  if not i in list(s):
    print(-1)
    break
    
T = list(t)
count=0
while len(T)>0:
  for i,n in enumerate(list(s*1000)):
    if T[0]==n:
      del T[0]
    if len(T)==0:
      print(i+1)
      break

Submission status: Wrong Answer

Solution code:
from collections import deque
import bisect
s = str(input())
t = str(input())

sc = [0] * 26
tc = [0] * 26

for i in range(len(s)):
    sc[ord(s[i]) - ord("a")] += 1
for i in range(len(t)):
    tc[ord(t[i]) - ord("a")] += 1

# 不可能な場合
for i in range(26):
    if tc[i] > 0 and sc[i] == 0:
        print(-1)
        exit()


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

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

alph_q = [alph[i] for i in range(26)]

ans = [0] * len(t)
pre_num = -1
for i in range(len(t)):
    num = ord(t[i]) - ord("a")
    if len(alph_q[num]) <= 0:
        alph_q[num] = alph[num]
    num_idx = alph_q[num][0]
    if i > 0:
        idx = bisect.bisect_right(alph_q[num], pre_num) - 1
        alph_q[num] = alph_q[num][idx+1:]
        if len(alph_q[num]) == 0:
            alph_q[num] = alph[num]
        num_idx = alph_q[num][0]
    ans[i] = num_idx
    pre_num = num_idx

count = 0
pre = -1
for v in ans:
    if pre >= v:
        count += 1
    pre = v

print(count * len(s) + ans[-1] + 1)

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
s_set=set([i for i in s])
t_set=set([i for i in t])
if t_set-s_set&t_set:
  print(-1)
  exit()
a={}
for i in t_set:
  a[i]=[]
  for k,j in enumerate(s):
    if j==i:
      a[i].append(k)
  a[i].sort()
ans=0
j=0
for i in t:
  if a[i][-1]<j:
    ans+=len(s)
    j=0
  for k in a[i]:
    if k>=j:
      j=k
      break
print(ans+j+1)

Submission status: Wrong Answer

Solution code:

import sys
#input = sys.stdin.readline

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

alpha2num = lambda c: ord(c) - ord('a') 

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

import bisect
tmp = 0
N = len(S)
base = 0
for t in T:
    a = alpha2num(t)
    if len(alpha[a]) == 0:
        print(-1)
        sys.exit()
    else:
        L = len(alpha[a])        
        num = bisect.bisect_right(alpha[a],tmp)
        
        if num == L:
            base += 1
            tmp = alpha[a][0]
        else:
            tmp = alpha[a][num]
            
            
ans = N * base + tmp + 1
print(ans)

Submission status: Wrong Answer

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

d = defaultdict(list)
for i in range(1, len(s)+1):
    d[s[i-1]].append(i)

ans = 0
currNum = 0
for w in t:
    if w in d:
        # 最初に戻る必要がある場合
        if max(d[w]) < currNum:
            ans += len(s)
            currNum = max(d[w])
        else:
            for i in d[w]:
                if currNum < i:
                    currNum = i
                    break
    else:
        ans = 0
        break

print(ans+currNum) if ans != 0 else print(-1)

Submission status: Wrong Answer

Solution code:
s=list(input())
t=list(input())
x=0
y=0
ans=0

for i in range(len(s)):
    s[i]=list(s[i])
    s[i].append(i)
for i in range(len(t)):
    t[i]=list(t[i])
    t[i].append(i)
s1=sorted(s)
t1=sorted(t)
dp=[0]*len(t)


for i in range(len(t)):
    for j in range(x,len(s)):
        if t1[i][0]==s1[j][0]:
            dp[t1[i][1]]=s1[j][1]
            x=j
            break
        if j==len(s)-1:
            print('-1')
            exit()

ans=dp[0]+1
for i in range(1,len(t)):
    if dp[i]<dp[i-1]:
        ans+=len(s)-dp[i-1]+dp[i]
    else:
        ans+=dp[i]-dp[i-1]
print(ans)

Submission status: Wrong Answer

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


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

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

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


def main():

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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    s = input()
    t = input()
    s_set = set(list(s))
    s_dict = {}
    s_len = len(s)
    t_list = list(t)
    c = 0
    ans = []
    ans_append = ans.append
    for i in s_set:
        s_dict[i] = []
    for i in range(s_len):
        s_dict[s[i]].append(i)
    if all([i in s_set for i in t_list]):
        for i in t_list:
            idxs = s_dict[i]
            if idxs[-1] <= c:
                c = idxs[0]
                ans_append(c)
            else:
                for idx in idxs:
                    if idx > c:
                        c = idx
                        ans_append(c)
                        break
        count = 0
        for i in range(len(ans)-1):
            if ans[i] >= ans[i+1]:
                count += 1
        print(s_len*count + ans[-1] + 1)
    else:
        print(-1)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

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

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

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

    from bisect import bisect

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


main()

Submission status: Wrong Answer

Solution code:
import sys

s = input()
t = input()

a = []
ls = len(s)
lt = len(t)

for i in t:
    try:
        a.append(s.index(i))
    except:
        print("-1")
        sys.exit()

p = 0
q = 0

for i in range(lt):
    if i > 0:
        if a[i - 1] > a[i]:
            p += 1
        else:
            q = a[i]

ans = p * ls + q + 1

print(ans)

Submission status: Wrong Answer

Solution code:
s=input()
t=input()
length=len(s)
pointer=0
flag=True
for string in t:
    count=0
    while flag and (string != s[pointer%length]):
        pointer+=1
        count+=1
        flag= not(count==length)
    if not flag:
        break
    count+=1
if flag:
    print(pointer+1)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/abc138/tasks/abc138_e

import string
s = input()
t = input()

d = dict(zip(string.ascii_lowercase, range(26)))    # アルファベットのdict
# print(d)
slist = [[] for _ in range(26)]
tlist = [[] for _ in range(26)]
# print(slist)

for i in range(len(s)):
    k = d[s[i]]
    slist[k].append(i)
# for j in range(len(t)):
#     k = d[t[j]]
#     tlist[k].append(j)

# print(slist)
# print(tlist)

ans = 1     # 1文字目から
i, j = 0, 0
while j < len(t):
    k = d[t[j]]
    if len(slist[k]) == 0:    # 無ければ -1
        ans = -1
        j = len(t)
    else:
        for l in range(len(slist[k])):  # 1巡目
            if slist[k][l] > i:
                ans += slist[k][l] - i  # 増えた分を加算
                i = slist[k][l]
                break   # 見つかったら次のt
        else:   # 見つからなかったら
            ans += slist[k][0] + len(s) - i  # 1周して増えた分を加算
            i = slist[k][0] # 1周して見つからなければ、最初のを選択
        j += 1  # 次のt

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
s = input()
t = input()
l = {}
for c in set(t):
    count = s.count(c)
    if count > 0:
        cl = []
        for i in range(count):
            cl.append(s.find(c, (0 if i==0 else cl[i-1] + 1)))
        l[c] = cl
    else:
        print("-1")
        sys.exit()
result = 0
for c in t:
    for i in l[c]:
        if i > result % len(s):
            result += i - (result % len(s))
            break
    else:
        result += len(s) - (result % len(s)) + l[c][0]
print(result+1)

Submission status: Wrong Answer

Solution code:
S = list(input())
T = list(input())

count = 0
ans = 0
j = 0
i = 0
error=0

if len(S)==1:
    for i in range(len(T)):
        if T[i]==S[0]:
            count += 1
    if count == len(T):
        print(count)
    else:
        print(-1)
        
else:        
    while True:
        if error >= 2:
            print(-1)
            break
        if count == len(T):
            print(ans+1)
            break
        if i == len(S):
            i = 0
            error += 1
        if S[i]==T[j]:
            count += 1
            j += 1
            error = 0
        else:
            i += 1
            ans += 1