Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

N, M = map(int,input().split())
dic = {}
P = []; Y = []
for i in range(M):
    p, y = map(int,input().split())
    P.append(p)
    Y.append(y)
    if p not in dic:
        dic[p] = [y]
    else:
        dic[p].append(y)

for p in dic.values():
    p.sort()

for i in range(M):
    print("{:06d}{:06d}".format(P[i], dic[P[i]].index(Y[i])+1))


### FIXED CODE ###

N, M = map(int,input().split())
dic = {}
P = []; Y = []
ans = ["" for i in range(M)]
for i in range(M):
    p, y = map(int,input().split())
    P.append(p)
    Y.append(y)
    if p not in dic:
        dic[p] = [[y,i]]
    else:
        dic[p].append([y,i])

for k,p in dic.items():
    p.sort()
    for pi in range(len(p)):
        ans[p[pi][1]] = "{:06d}{:06d}".format(k,pi+1)

for i in range(M):
    print(ans[i])
### BUGGY CODE ###

import itertools

N = int(input())
S = list(input())

rgb = S.count('R')*S.count('G')*S.count('B')

ans = 0
for comb in list(itertools.combinations(range(N), 2)):
  i, j = comb
  
  if (j*2 -i) < N:
    if (S[i] != S[j]) & (S[j] != S[j*2 -i]) & (S[j*2 -i] != S[i]) :
      ans += 1

print(rgb - ans)

### FIXED CODE ###

from collections import Counter

N = int(input())
S = list(input())

cnt = Counter(S)

ans = cnt['R'] * cnt['G'] * cnt['B']

for i in range(N):
  for j in range(i+1, N):
    k = j + j - i
    if k < N :
      if (S[i] == S[j]) or (S[j] == S[k]) or (S[k] == S[i]) :
        continue
      ans -= 1

print(ans)
### BUGGY CODE ###

def move(start,end,city):
    if( a[start-1] > city[start]):
        # tmp1 = city[start]
        city[end] += city[start]
        city[start] = 0
    else:
        city[end] += a[start-1]
        city[start] -= a[start-1]
    return city

n = int(input())
a = [int(input()) for i in range(5)]
city = [0,n,0,0,0,0,0,0]

time = 0
while(city[6] < n):
    time += 1
    for i in range(5):
        city = move(5-i,6-i,city)
print(time)

### FIXED CODE ###

N = int(input())
A = [int(input()) for _ in range(5)]
print(-(-N // min(A))+4)
### BUGGY CODE ###

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(1000000000)

N = int(input())
MOD = 10**9 + 7

neighbor = [[] for _ in range(N)]
for _ in range(N-1):
    x,y = map(int, input().split())
    neighbor[x-1].append(y-1)
    neighbor[y-1].append(x-1)

def dp(node, color, parent):
    output = 1
    for child in neighbor[node]:
        if child == parent:
            pass
        else:
            tmp = dp(child, 0, node)
            if color == 0:
                tmp += dp(child, 1, node)
                tmp %= MOD
            output *= tmp
            output %= MOD
    return output

print((dp(0,0,-1) + dp(0,1,-1)) % MOD)

### FIXED CODE ###

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(1000000000)

N, *XY = map(int,open(0).read().split())
MOD = 10**9 + 7

neighbor = [[] for _ in range(N)]
for x,y in zip(*[iter(XY)]*2):
    neighbor[x-1] += y-1,
    neighbor[y-1] += x-1,

parent = {0}

def dp(node):
    black_output = white_output = 1
    for child in neighbor[node]:
        if child in parent:
            continue
        else:
            parent.add(child)
            tmp_black, tmp_white = dp(child)
            black_output *= tmp_white
            white_output *= tmp_black + tmp_white
    black_output %= MOD
    white_output %= MOD
    return black_output, white_output

print(sum(dp(0)) % MOD)
### BUGGY CODE ###

N = int(input())
d = list(map(int, input().split()))
d.sort()

s, t = N//2-1, N//2

cnt = 0
for i in range(d[s],d[t]+1):
    tmp = [x>=i for x in d]
    if tmp.count(True)==tmp.count(False):
        cnt += 1
print(cnt)

### FIXED CODE ###

N = int(input())
d = list(map(int, input().split()))
d.sort()

s, t = N//2-1, N//2

ans = d[t] - d[s]
print(ans)
### BUGGY CODE ###

def slove():
    import sys
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ls = [0] * n
    mt = [0] * n
    cnt = 0
    bbb = 0

    for i in range(n):
        if ls[i] != -1:
            mt[i] = a[i][ls[i]]

    for w in range(10 ** 15):
        cnt += 1
        f = [False] * n
        bb = False
        update = []
        for i in range(n):
            if not f[i]:
                if ls[i] != -1:
                    if i + 1 == mt[mt[i]-1]:
                        f[i] = True
                        f[mt[i]-1] = True
                        bb = True
                        if ls[i] + 1 < n - 1:
                            ls[i] += 1
                            update.append(i)
                        else:
                            ls[i] = -1
                            bbb += 1

                        if ls[mt[i]-1] + 1 < n - 1:
                            ls[mt[i]-1] += 1
                            update.append(mt[i]-1)
                        else:
                            ls[mt[i]-1] = -1
                            bbb += 1
        for i in update:
            if ls[i] != -1:
                mt[i] = a[i][ls[i]]

        if bbb == n:
            print(cnt)
            exit()
        if not bb:
            print(-1)
            exit()


if __name__ == '__main__':
    slove()


### FIXED CODE ###

def slove():
    import sys
    import collections
    input = sys.stdin.readline
    n = int(input().rstrip('\n'))
    a = [list(map(int, input().rstrip('\n').split())) for _ in range(n)]
    ad = [0] * n
    dq = collections.deque([[0, i + 1] for i in range(n)])
    for i in range(10 ** 15):
        fd = {}
        while True:
            if len(dq) != 0:
                d, q = dq.popleft()
                q -= 1
                if d <= i:
                    if ad[q] < n - 1:
                        qq = a[q][ad[q]] - 1
                        tq = a[qq][ad[qq]] - 1
                        if q == tq and qq not in fd and tq not in fd:
                            ad[qq] += 1
                            ad[tq] += 1
                            if ad[qq] < n - 1:
                                dq.append([d + 1, qq + 1])
                            if ad[tq] < n - 1:
                                dq.append([d + 1, tq + 1])
                            fd[qq] = 0
                            fd[tq] = 0
                else:
                    dq.append([d, q + 1])
                    break
            else:
                break
        if len(dq) == 0:
            b = True
            for v in ad:
                if v != n - 1:
                    b = False
                    break
            if b:
                print(i + 1)
                exit()
            else:
                print(-1)
                exit()


if __name__ == '__main__':
    slove()
### BUGGY CODE ###

n,q=map(int,input().split())
s=input()
f=[0]*n
for i in range(n-1):
  if s[i:i+2]=="AC":f[i]=1
for i in range(q):
  l,r=map(int,input().split())
  print(sum(f[l-1:r-1]))

### FIXED CODE ###

n,q=map(int,input().split())
l=[0 for i in range(n)]
for i,v in enumerate(list(input().replace("AC","X!"))):
    l[i]=l[i-1]+(v=="!")
for c in range(q):
    h,m=map(int,input().split())
    print(l[m-1]-l[h-1])
### BUGGY CODE ###

n = int(input())
a = [int(x) for x in input().split()]
q = int(input())
bc=[]
for i in range(q):
    bc.append([int(x) for x in input().split()])

for gyou in range(q):
	a=[bc[gyou][1] if i==bc[gyou][0] else i for i in a]
	print(sum(a))


### FIXED CODE ###

n = int(input())
a = [int(x) for x in input().split()]
q = int(input())
bc=[]
for i in range(q):
    bc.append([int(x) for x in input().split()])

a_cnt=[0]*(10**5+1)

for i in range(len(a)):
	a_cnt[a[i]]+=1

a_goukei=sum(a)

for gyou in range(q):
	a_goukei+=(bc[gyou][1]-bc[gyou][0])*a_cnt[bc[gyou][0]]
	print(a_goukei)
	a_cnt[bc[gyou][1]]+=a_cnt[bc[gyou][0]]
	a_cnt[bc[gyou][0]]=0
### BUGGY CODE ###

import statistics as stat
import collections as cl

N = int(input())

s_li = []
c = 0
for i in range(N) :
    s = sorted(list(input()))
    for s_item in s_li :
        if (s == s_item) :
            c += 1
    s_li.append(s)


print(c)

### FIXED CODE ###

import statistics as stat
import collections as cl

N = int(input())

s_li = []
s_dic = {}
c = 0
for i in range(N) :
    s = ''.join(sorted(list(input())))
    # con = s_li.count(s)
    # if (con >= 1) :
    #     c += con
    # s_li.append(s)
    if (s in s_dic) :
        c += s_dic[s]
        s_dic[s] += 1
    else :
        s_dic[s] = 1

print(c)
### BUGGY CODE ###

import numpy as np
#降順ソートの方がうまくいきそう
n,m=map(int,input().split())
a=np.sort(np.array(list(map(int,input().split()))))[::-1]
cs=np.cumsum(a)

#和が引数以上の場合をカウントする
def overX(x):
	count=0
	#両手が違う人を握るときのみ考える
	if a[0]*2<x:
		return 0
	else:
		for i in range(n):
			if a[i]+a[0]<x:
				count+=0
			else:
				lb, ub = 0, n
				#パターンAのにぶたん。左がOなので[lb,ub)で持つ。
				while ub-lb>1:
					mid=(lb+ub)//2
					if a[i]+a[mid]>=x:
						lb=mid
					else:
						ub=mid
				count+=lb+1
		return count
#print(overX(130))

#overX>=mなる最大のxを探す->xは小さい方が実現しやすいのでパターンA->[lb,ub)でもつ
lb=1 #実現しやすい方
ub=2*10**5
while ub-lb>1:
	mid=(ub+lb)//2
	if overX(mid)>=m:
		lb=mid
	else:
		ub=mid
#ub=overX(x)>=mなる最小のx。これ以上大きくするとmに満たなくなる。
maxx=lb

hp=0
#maxx+1以上の要素をすべてたす
#和がmaxx+1以上になる組み合わせの数だけhpを加え、countをインクリメントする
if a[0]*2>=maxx+1:
	for i in range(n):
		if a[i]+a[0]<maxx+1:
			break
		else:
			lb, ub = 0, n
			#パターンAのにぶたん。左がOなので[lb,ub)で持つ。
			while ub-lb>1:
				mid=(lb+ub)//2
				if a[i]+a[mid]>=maxx+1:
					lb=mid
				else:
					ub=mid
			#a[0]からa[lb]は、a[i]と足した時にx以上になり条件を満たす。
			hp+=a[i]*(lb+1)+cs[lb]
'''print(hp)
print(overX(maxx))
print(overX(maxx+1))
print(maxx)'''
hp+=(m-overX(maxx+1))*maxx
print(hp)

### FIXED CODE ###

#降順ソートの方がうまくいきそう
n,m=map(int,input().split())
a=sorted(list(map(int,input().split())),reverse=True)
cs=[]
sum=0
for i in range(n):
	sum+=a[i]
	cs.append(sum)

#和が引数以上の場合をカウントする
def overX(x):
	count=0
	#両手が違う人を握るときのみ考える
	if a[0]*2<x:
		return 0
	else:
		for i in range(n):
			if a[i]+a[0]<x:
				count+=0
			else:
				lb, ub = 0, n
				#パターンAのにぶたん。左がOなので[lb,ub)で持つ。
				while ub-lb>1:
					mid=(lb+ub)//2
					if a[i]+a[mid]>=x:
						lb=mid
					else:
						ub=mid
				count+=lb+1
		return count
#print(overX(130))

#overX>=mなる最大のxを探す->xは小さい方が実現しやすいのでパターンA->[lb,ub)でもつ
lb=1 #実現しやすい方
ub=2*10**5+1
while ub-lb>1:
	mid=(ub+lb)//2
	if overX(mid)>=m:
		lb=mid
	else:
		ub=mid
#ub=overX(x)>=mなる最小のx。これ以上大きくするとmに満たなくなる。
maxx=lb

hp=0
#maxx+1以上の要素をすべてたす
#和がmaxx+1以上になる組み合わせの数だけhpを加え、countをインクリメントする
if a[0]*2>=maxx+1:
	for i in range(n):
		if a[i]+a[0]<maxx+1:
			break
		else:
			lb, ub = 0, n
			#パターンAのにぶたん。左がOなので[lb,ub)で持つ。
			while ub-lb>1:
				mid=(lb+ub)//2
				if a[i]+a[mid]>=maxx+1:
					lb=mid
				else:
					ub=mid
			#a[0]からa[lb]は、a[i]と足した時にx以上になり条件を満たす。
			hp+=a[i]*(lb+1)+cs[lb]
hp+=(m-overX(maxx+1))*maxx
print(hp)
### BUGGY CODE ###

import  collections

s = input().strip()
t = []
for i in range(len(s)):
    t.append(int(s[i:]) % 2019)
    
t.append(0)
count = dict(collections.Counter(t))
tot = 0
for c in count.values():
    tot += c*(c-1)/2
print(int(tot))

### FIXED CODE ###

import numpy as np

s = input().strip()
t = 0
counts = np.array([0] * 2019)
counts[0] += 1
m = 1

for a  in reversed(s):
    t = (t + m * int(a)) % 2019
    counts[t] += 1
    m = m * 10 % 2019
    
print(int(np.sum(counts * (counts - 1) /2)))
### BUGGY CODE ###


def main():
    n = int(input())
    a_list = map(int, input().split())

    result = 1

    for a in a_list:
        result = result * a

    if result > 10**18:
        print('-1')
        return

    print(result)


if __name__ == "__main__":
    main()


### FIXED CODE ###


def main():
    n = int(input())
    a_list = list(map(int, input().split()))

    a_list = list(filter((1).__ne__, a_list))

    if 0 in a_list:
        print('0')
        return

    result = 1

    for a in a_list:
        result = result * a

        if result > 10**18:
            print('-1')
            return

    print(result)


if __name__ == "__main__":
    main()
### BUGGY CODE ###

# https://atcoder.jp/contests/abc154/tasks/abc154_d
import numpy as np
N, K = map(int, input().split())
p = np.array(list(map(int, input().split())))

v = 0
idx = -1
for i in range(N):
    tmp = p[i:i + K].sum()
    if tmp > v:
        v = tmp
        idx = i

# print('v idx', v, idx)
subset = p[idx:idx + K]
ans = ((subset + 1) / 2).sum()
print(ans)


### FIXED CODE ###

# https://atcoder.jp/contests/abc154/tasks/abc154_d
import numpy as np
N, K = map(int, input().split())
p = np.array(list(map(int, input().split())))
p = (p + 1) / 2
cumsum = np.cumsum(np.array(p))
tmp = np.pad(cumsum[:-K], [K, 0], 'constant')
print((cumsum - tmp).max())
### BUGGY CODE ###

P = [0] * 100001
Q = [0] * 100002
P[0] = 1
P[1] = 1

for i in range(2, 100000):
    if P[i] == 0:
        for j in range(i*2, 100000, i):
            P[j] += 1

n = int(input())
num = [list(map(int,input().split())) for _ in range(n)]

for k in range(3, 100000, 2):
    if P[k] == 0 and P[(k + 1) // 2] == 0:
        Q[k] += 1

for l in range(n):
    print(Q[:num[l][1]+1].count(1) - Q[:num[l][0]].count(1))

### FIXED CODE ###

from collections import Counter
P = [0] * 100001
Q = [0] * 100002
P[0] = 1
P[1] = 1

for i in range(2, 100000):
    if P[i] == 0:
        for j in range(i*2, 100000, i):
            P[j] += 1

n = int(input())
num = [list(map(int,input().split())) for _ in range(n)]

for k in range(3, 100000, 2):
    if P[k] == 0 and P[(k + 1) // 2] == 0:
        Q[k] = 1
for l in range(100000):
    Q[l+1] += Q[l]

for m in range(n):
    l, r = num[m][0], num[m][1]
    print(Q[r] - Q[l-1])
### BUGGY CODE ###

def main():
  from collections import defaultdict
  from heapq import heappush,heappop
  inf=10**12
  n,m,*t=map(int,open(0).read().split())
  edge=defaultdict(list)
  used,d={},{}
  l=[]
  for a,b,c in zip(t[::3],t[1::3],t[2::3]):
    if b<a:a,b=b,a
    x,y=a+n*c,b+n*c
    if b==n:l.append(y)
    edge[a].append((1,x))
    edge[b].append((1,y))
    ex,ey=edge[x].append,edge[y].append
    ex((0,a))
    ex((0,y))
    ey((0,b))
    ey((0,x))
    used[a]=used[b]=used[x]=used[y]=True
    d[a]=d[b]=d[x]=d[y]=inf
  d[1]=0
  used[1]=False
  edgelist=[]
  for e in edge[1]:
    heappush(edgelist,e)
  while edgelist:
    c,v=heappop(edgelist)
    if not used[v]:
      continue
    d[v]=c
    used[v]=False
    for o,e in edge[v]:
      if used[e]:
        heappush(edgelist,(c+o,e))
  a=min([d[i]for i in set(l)]or[inf])
  print([a,-1][a==inf])
if __name__=='__main__':
  main()

### FIXED CODE ###

def main():
  from heapq import heappush,heappop,heapify
  inf=2**31-1
  n,m,*t=map(int,open(0).read().split())
  z=[]
  for a,b,c in zip(t[::3],t[1::3],t[2::3]):
    z.extend([a,b,a+n*c,b+n*c])
  z={i:v for v,i in enumerate(sorted(set(z)))}
  try:
    z[1]
  except:
    print(-1)
    exit()
  edge=[[]for _ in range(len(z))]
  d={}
  l=[]
  for a,b,c in zip(t[::3],t[1::3],t[2::3]):
    if b<a:a,b=b,a
    i,j,x,y=z[a],z[b],z[a+n*c],z[b+n*c]
    if b==n:
      l.append(y)
    edge[i].append((1,x))
    edge[j].append((1,y))
    edge[x].extend([(0,i),(0,y)])
    edge[y].extend([(0,j),(0,x)])
  used=[False]+[True]*~-len(z)
  d=[0]+[inf]*~-len(z)
  edgelist=edge[0]
  heapify(edgelist)
  while edgelist:
    m=heappop(edgelist)
    if not used[m[1]]:
      continue
    d[m[1]]=m[0]
    used[m[1]]=False
    for e in edge[m[1]]:
      if used[e[1]]:
        heappush(edgelist,(e[0]+m[0],e[1]))
  a=min([d[i]for i in l]or[inf])
  print([a,-1][a==inf])
if __name__=='__main__':
  main()
### BUGGY CODE ###

import bisect
import collections

n=int(input())
arr=[0]+list(map(int,input().split()))
g=[[] for _ in range(n+1)]
for _ in range(n-1):
  a,b=map(int,input().split())
  g[a].append(b)
  g[b].append(a)
ans=[0]*(n+1)
checked=[0]*(n+1)
checked[1]=1
q=collections.deque()
q.append((1,1,[arr[1]]))
while len(q)!=0:
  v,l,tr=q.popleft()
  ans[v]=l
  for u in g[v]:
    if checked[u]==0:
      checked[u]=1
      pos=bisect.bisect_left(tr,arr[u])
      if pos==l:
        q.append((u,l+1,tr+[arr[u]]))
      elif tr[pos]==arr[u]:
        q.append((u,l,tr))
      else:
        q.append((u,l,tr[:pos]+[arr[u]]+tr[pos+1:]))
for i in range(1,n+1):
  print(ans[i])

### FIXED CODE ###

import bisect
import sys
sys.setrecursionlimit(10**7)

def dfs(v):
  pos=bisect.bisect_left(dp,arr[v])
  changes.append((pos,dp[pos]))
  dp[pos]=arr[v]
  ans[v]=bisect.bisect_left(dp,10**18)
  for u in g[v]:
    if checked[u]==0:
      checked[u]=1
      dfs(u)
  pos,val=changes.pop()
  dp[pos]=val

n=int(input())
arr=[0]+list(map(int,input().split()))
g=[[] for _ in range(n+1)]
for _ in range(n-1):
  a,b=map(int,input().split())
  g[a].append(b)
  g[b].append(a)
ans=[0]*(n+1)
checked=[0]*(n+1)
checked[1]=1
dp=[10**18 for _ in range(n+1)]
changes=[]
dfs(1)
for i in range(1,n+1):
  print(ans[i])
### BUGGY CODE ###

# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

def main():
    N, Q = lr()
    STX = [tuple(lr()) for _ in range(N)]
    event = []
    for s, t, x in STX:
        event.append((s-x, 0, x))
        event.append((t-x, -1, x))

    for i in range(Q):
        d = ir()
        event.append((d, 1, i))

    event.sort()
    answer = [-1] * Q
    cur = set()
    flag = False
    INF = 10 ** 10
    min_x = INF
    for a, b, c in event:
        if b == 0:
            cur.add(c)
            if c < min_x:
                min_x = c
                flag = True
        elif b == -1:
            cur.remove(c)
            if min_x == c:
                flag = False
        elif b == 1:
            if cur:
                if not flag:
                    min_x = min(cur)
                    flag = True
                answer[c] = min_x

    print('\n'.join(map(str, answer)))

if __name__ == "__main__":
    main()


### FIXED CODE ###

# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, Q = lr()
STX = [tuple(lr()) for _ in range(N)]
event = []
for s, t, x in STX:
    event.append((s-x, 0, x))
    event.append((t-x, -1, x))

for i in range(Q):
    d = ir()
    event.append((d, 1, i))

event.sort()
answer = [-1] * Q
cur = set()
flag = False
INF = 10 ** 10
min_x = INF
for a, b, c in event:
    if b == 0:
        cur.add(c)
        if c < min_x:
            min_x = c
            flag = True
    elif b == -1:
        cur.remove(c)
        if min_x == c:
            flag = False
    elif b == 1:
        if cur:
            if not flag:
                min_x = min(cur)
                flag = True
            answer[c] = min_x

print('\n'.join(map(str, answer)))
# 19
### BUGGY CODE ###

N = int(input())
p_list  = list(map(int,input().strip().split(" ")))

c = 1

for i in range(N):
    temp = 0
    for j in range(i):
        if p_list[i] <= p_list[j]:
            temp += 1
            if temp == i:
                c += 1
        else:
            break
print(c)


### FIXED CODE ###

N = int(input())
p_list  = list(map(int,input().strip().split(" ")))

ans = 1
mi = p_list[0]

for i in range(1, N):
    if mi >= p_list[i]:
        ans += 1
        mi = p_list[i]
        
print(ans)
### BUGGY CODE ###

n, x = map(int, input().split())
li = list(map(int, input().split()))
t = []
for i in li:
    t.append(abs(i - x))
for j in range(min(t)):
    if all(k % (min(t) - j) == 0 for k in t):
        print(min(t) - j)
        exit()


### FIXED CODE ###

n, x = map(int, input().split())
li = list(map(int, input().split()))
t = []
for i in li:
    t.append(abs(i - x))
divisors = []
for i in range(1, int(min(t) ** 0.5) + 1):
    if min(t) % i == 0:
        divisors.append(i)
        if i != min(t) // i:
            divisors.append(min(t) // i)
divisors.sort()
divisors = divisors[::-1]
for j in divisors:
    if all(k % j == 0 for k in t):
        print(j)
        exit()
### BUGGY CODE ###

N, Q = map(int, input().split())
S = input()

ans = [0] * N

for i in range(1, N):
    if S[i-1]=="A" and S[i]=="C":
        ans[i] = 1

for i in range(Q):
    l, r = map(int, input().split())
    print(sum(ans[0:r]) - sum(ans[0:l]))




### FIXED CODE ###


N, Q = map(int, input().split())
S = list(input())
lr = []
for i in range(Q):
    l, r = map(int, input().split())
    lr.append([l-1, r-1])
AC = []
pre = None
cnt = 0
for c in S:
    if c == "A":
        pre = "A"
    elif pre == "A" and c == "C":
        cnt += 1
        pre = None
    elif pre == "A":
        pre = None
    AC.append(cnt)
for l, r in lr:
    print(AC[r] - AC[l])
### BUGGY CODE ###

from collections import deque
import bisect

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

pos_S = {}
for i, s in enumerate(S):
  if s in pos_S:
    pos_S[s].append(i)
  else:
    pos_S[s] = deque([i])
x = 0
start = 0
for t in T:
  if t in pos_S:
    poss = pos_S[t]
    pos = bisect.bisect_left(poss, start)
    if pos >= len(poss):
      x += 1
      start = poss[0]+1
    else:
      start = poss[pos]+1
  else:
    x = -1
    break
if x == -1:
  print(-1)
else:
  print(x*len(S)+start)



### FIXED CODE ###

from collections import deque
import bisect

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

pos_S = {}
for i, s in enumerate(S):
  if s in pos_S:
    pos_S[s].append(i)
  else:
    pos_S[s] = deque([i])
x = 0
start = 0
for t in T:
  if t in pos_S:
    poss = pos_S[t]
    pos = bisect.bisect_left(poss, start)
    if pos >= len(poss):
      x += 1
      start = poss[0]+1
    else:
      start = poss[pos]+1
  else:
    x = -1
    break
if x == -1:
  print(-1)
else:
  print(x*len(S)+start)
### BUGGY CODE ###

n = int(input())
A = list(map(int, input().split()))

ans = [A.index(i+1)+1 for i in range(n)]
print(*ans)  

### FIXED CODE ###

N = int(input())
keys = list(map(int, input().split()))

values = [i for i in range(1, N+1)]
dic = dict(zip(keys, values))
keys.sort()
for i in range(1, N+1):
    value = dic[i]
    print('{} '.format(value), end='')
### BUGGY CODE ###

n,m = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)
for i in range(m):
    a[0] = a[0]//2
    a.sort(reverse=True)
print(sum(a))

### FIXED CODE ###

import heapq

n,m = map(int, input().split())

a = [-i for i in list(map(int, input().split()))]
heapq.heapify(a)

for i in range(m):
    p = heapq.heappop(a)
    p = (-p)//2
    heapq.heappush(a, -p)
    
print(-sum(a))
### BUGGY CODE ###

import sys,math,collections,itertools
input = sys.stdin.readline

s = input().rstrip()
K = int(input())
ls = len(s)
cs = []
for i in range(ls):
    for j in range(i+1,ls+1):
        cs.append(s[i:j])
os = sorted(cs)
count = 0
lis = []
for i in os:
    if i not in lis:
        lis.append(i)
        count +=1
    else:
        continue
    if count == K:
        print(i)
        exit()
    


### FIXED CODE ###

import sys,collections
input = sys.stdin.readline

s = input().rstrip()
K = int(input())
ls = len(s)
cs = collections.deque()
for i in range(ls):
    for j in range(i+1,i+1+K):
        cs.append(s[i:j])
os = sorted(cs)
count = 0
lis = []
for i in os:
    if i not in lis:
        lis.append(i)
        count +=1
    else:
        continue
    if count == K:
        print(i)
        exit()
### BUGGY CODE ###

def main():
    N = int(input())
    # [4, 3, 3, 1, 3, 2]
    A = [int(input()) for _ in range(N)]
    current_max = max(A[1:N])
    # print('---')
    print(current_max)
    previous_max = current_max
    for i in range(1, N):
        if A[i] != previous_max:
            current_max = max([A[i-1], previous_max])
        else:
            current_max = max(A[0:i] + A[i+1:N])
        print(current_max)
        previous_max = current_max


if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    N = int(input())
    # [4, 3, 3, 1, 3, 2]
    A = [int(input()) for _ in range(N)]
    current_max = max(A[1:N])
    current_max_index = A.index(current_max)
    # print('---')
    print(current_max)
    previous_max = current_max
    previous_max_index = current_max_index
    for i in range(1, N):
        # A_tmp = A[0:i] + A[i+1:N]
        if i != previous_max_index:
            current_max = max([A[i-1], previous_max])
            current_max_index = previous_max_index
        else:
            current_max = max(A[0:i] + A[i+1:N])
            current_max_index = A.index(current_max)
        print(current_max)
        previous_max = current_max
        previous_max_index = current_max_index


if __name__ == '__main__':
    main()