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

from heapq import*
i=input
for _ in'_'*int(i()):
 n,s,x,*y=int(i()),0,[];exec('k,l,r=t=[*map(int,i().split())];x+=[t]*(l>r);y+=[(n-k,r,l)]*(l<=r);'*n)
 for x in x,y:
  x.sort();n,*h=len(x),
  while n:
   n-=1
   while x and x[-1][0]>n:k,l,r=x.pop();heappush(h,(r-l,l,r))
   if h:s+=heappop(h)[1]
  for*_,r in x+h:s+=r
 print(s)

### FIXED CODE ###

import sys
from heapq import*
input=sys.stdin.buffer.readline
def solve():
    n=int(input())
    x,y=[],[]
    for _ in range(n):
        k,l,r=map(int,input().split())
        if l>r:
            x+=(k,l,r),
        else:
            y+=(n-k,r,l),
    x.sort()
    y.sort()
    s=0
    h=[]
    for i in range(len(x),0,-1):
        while x and x[-1][0]>=i:
            k,l,r=x.pop()
            heappush(h,(r-l,l,r))
        if h:s+=heappop(h)[1]
    s+=sum(r for _,_,r in x+h)
    h=[]
    for i in range(len(y),0,-1):
        while y and y[-1][0]>=i:
            k,l,r=y.pop()
            heappush(h,(r-l,l,r))
        if h:s+=heappop(h)[1]
    s+=sum(r for _,_,r in y+h)
    return s
t=int(input())
print('\n'.join(str(solve())for _ in range(t)))
### BUGGY CODE ###

import itertools

N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))

length = len(V)
conb = []
for i in range(length+1):
    conb.append(list(itertools.combinations(V,i)))

cost = []
for c in conb:
    for i in c:
        idx = []
        x = 0
        y = 0
        for k in i:
            idx.append(V.index(k))
        for a in idx:
            x += V[a]
            y += C[a]
        cost.append(x-y)

print(max(cost))


### FIXED CODE ###

N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))

ans = sum([ max( 0, (V[i]-C[i]) ) for i in range(N) ])

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

n = input()
s = list(input())
 
ans = len(s)

sharp = 0
dot = 0
for string in s:
	if(string == "#"):
		sharp += 1
	else:
		dot += 1 

for i in range(len(s)):
	temp_ans = 0
	for j in range(0, i):
		if(s[j]) == "#":
			temp_ans += 1
	for j in range(i,len(s)):
		if (s[j] == "."):
			temp_ans += 1
	ans = min(ans, temp_ans, len(s) - dot)
 
print(ans)

### FIXED CODE ###

n = input()
s = list(input())
 
ans = len(s)

sharp = 0
dot = 0
for string in s:
	if(string == "#"):
		sharp += 1
	else:
		dot += 1 

left_sharp = 0
right_dot = dot

for i in range(len(s)):
	temp_ans = left_sharp + right_dot
	ans = min(ans,temp_ans)
	if(s[i] == "."):
		right_dot -= 1
	else:
		left_sharp += 1

ans = min(ans, len(s) - dot) 

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

n,k = input().split()
n=int(n)
k=int(k)
h = [int(input()) for i in range(n)]
h.sort()
#print(h)
ans=10000000000

for i in range(n-k+1):
  list1 = [h[j] for j in range(i,i+k)]
#  print(list1)
  if max(list1)-min(list1) < ans:
      ans = max(list1)-min(list1)
print(ans)

### FIXED CODE ###

n,k = input().split()
n=int(n)
k=int(k)
h = [int(input()) for i in range(n)]
h.sort()
#print(h)
ans=10000000000

for i in range(n-k+1):
#  list1 = [h[j] for j in range(i,i+k)]
#  print(list1)
  if h[i+k-1]-h[i] < ans:
      ans = h[i+k-1]-h[i]
print(ans)
### BUGGY CODE ###

n = int(input())
S = list(map(int,input().split()))
q = int(input())
T = list(map(int,input().split()))

sum = 0
for c in T:
    left = 0
    right = n
    mid = 0
    while left < right:
        mid = int(( left + right ) / 2)
        if c == S[mid]:
            sum += 1
            break
print(sum)

### FIXED CODE ###

n = int(input())
S = list(map(int,input().split()))
q = int(input())
T = list(map(int,input().split()))

sum = 0
for c in T:
    left = 0
    right = n
    mid = 0
    if c == S[left] or c == S[right-1]:
        sum += 1
    else:
        while left+1 < right:
            mid = int(( left + right ) / 2)
            if c == S[mid]:
                sum += 1
                break
            if c > S[mid]:
                left = mid
                mid = 0
            elif c < S[mid]:
                right = mid
                mid = 0
print(sum)
### BUGGY CODE ###

N, M = map(int, input().split())
A = list(int(input()) for _ in range(M))
P = 10**9 + 7

dp = [0] * (N+1)
dp[0] = 1
dp[1] = 1 if 1 not in A else 0
for i in range(2, N+1):
    if i not in A:
        dp[i] = dp[i-1] + dp[i-2]
    else:
        dp[i] = 0
print(dp[N]%P)

### FIXED CODE ###

N, M = map(int, input().split())
if N == 1:
    print(1)
    quit()
if M > N//2:
    print(0)
    quit()

A = list(int(input()) for _ in range(M))
idx = 0
P = 10**9 + 7

dp = [0] * (N+1)
dp[0] = 1
dp[1] = 1
a = -1
if len(A):
    if 1 == A[idx]:
        dp[1] = 0
        if idx < M-1:
            idx += 1

if len(A):
    for i in range(2, N+1):
        if i != A[idx]:
            dp[i] = (dp[i-1] + dp[i-2]) % P
        else:
            dp[i] = 0
            if idx < M-1:
                idx += 1
else:
    for i in range(2, N+1):
        dp[i] = (dp[i-1] + dp[i-2]) % P
print(dp[N])
### BUGGY CODE ###

N = int(input())
ans = 1
mod = 10 ** 9 + 7

for i in range(1, N+1):
    ans *= i

print(ans % mod)


### FIXED CODE ###

import math

N = int(input())
mod = 10 ** 9 + 7
print(math.factorial(N) % mod)
### BUGGY CODE ###

def solve():
    MOD = 10**9 + 7

    N = int(input())
    Ass = [tuple(map(int, input().split())) for _ in range(N)]

    dp = [0] * (1<<N)
    dp[0] = 1
    for S in range(1, 1<<N):
        iM = bin(S).count('1') - 1
        for iW in range(N):
            if S & (1<<iW) and Ass[iM][iW]:
                S0 = S ^ (1<<iW)
                dp[S] += dp[S0]
        dp[S] %= MOD

    print(dp[-1])


solve()


### FIXED CODE ###

MOD = 10**9 + 7

N = int(input())
As = [int(input().replace(' ', ''), 2) for _ in range(N)]

patWsList = [[] for _ in range(N+1)]
for patW in range(2**N):
    num1 = sum([(patW >> i) & 1 for i in range(N)])
    patWsList[num1].append(patW)

dp = [0] * (2**N)
dp[-1] = 1
for iM, (A, patWs) in enumerate(zip(As, reversed(patWsList))):
    for patW in patWs:
        A2 = A & patW
        dpNow = dp[patW]
        for iW in range(N):
            if A2 & (1 << iW):
                dp[patW ^ (1 << iW)] += dpNow
                dp[patW ^ (1 << iW)] %= MOD

print(dp[0])
### BUGGY CODE ###

import heapq

n,m,s,t = map(int,input().split())
inf = 1000000000000000
gyen = [[] for _ in range(n)]
gsnuuk = [[] for _ in range(n)]

for _ in range(m):
        u,v,a,b = map(int,input().split())
        gyen[u-1].append([v-1,a])
        gyen[v-1].append([u-1,a])
        gsnuuk[u-1].append([v-1,b])
        gsnuuk[v-1].append([u-1,b])

def dijkstra(graph, start):
        dist = [inf for _ in range(n)]
        dist[start] = 0
        q = [(0,start)]
        while q:
                du, u = heapq.heappop(q)
                if dist[u] < du:
                        continue
                for i in graph[u]:
                        if dist[i[0]] > du+i[1]:
                                dist[i[0]] = du+i[1]
                                heapq.heappush(q, (dist[i[0]], i[0]))
        return dist

dist_from_start = dijkstra(gyen,s-1)
dist_from_goal = dijkstra(gsnuuk,t-1)

for i in range(n):
        ans = inf
        for j in range(i,n):
                tmp = dist_from_start[j] + dist_from_goal[j]
                if tmp < ans:
                        ans = tmp
        print(inf - ans)

### FIXED CODE ###

import heapq
import sys
from itertools import accumulate

n,m,s,t = map(int,next(sys.stdin).split(" "))
inf = 1000000000000000
gyen = [dict() for _ in range(n)]
gsnuk = [dict() for _ in range(n)]

for _ in range(m):
        u,v,a,b = map(int,next(sys.stdin).split(" "))
        gyen[u-1][v-1] = gyen[v-1][u-1] = a
        gsnuk[u-1][v-1] = gsnuk[v-1][u-1] = b

def dijkstra(graph, start):
        dist = [inf for _ in range(n)]
        dist[start] = 0
        q = [(0,start)]
        while q:
                du, u = heapq.heappop(q)
                if dist[u] < du:
                        continue
                for v,d in graph[u].items():
                        if dist[v] > du+d:
                                dist[v] = du+d
                                heapq.heappush(q, (dist[v], v))
        return dist

yen = dijkstra(gyen,s-1)
snuke = dijkstra(gsnuk,t-1)

ans = list(accumulate([y+s for y,s in zip(yen,snuke)][::-1],min))
[print(inf-ans[i]) for i in range(n-1,-1,-1)]
### BUGGY CODE ###

N = int(input())
A = [int(i) for i in input().split(' ')]

A.sort(reverse=True)
ring = []
max_value = A.pop(0)
ring.append(max_value)
ring.append(max_value)
ans = 0
flag = True
while len(A) != 0:
    i = A.pop(0)
    n = []
    if flag:
        for j in range(0, len(ring) - 1):
            check = min(ring[j:j + 2])
            n.append(check)
            flag = False
            if check == max(ring):
                break
    else:
        for j in range(len(ring), 1, -1):
            check = min(ring[j - 2:j])
            n.append(check)
            flag = True
            if check == max(ring):
                break
    ans = ans + max(n)
    ring.insert(n.index(max(n)) + 1, i)

print(ans)

### FIXED CODE ###

import sys
from collections import deque

N = int(sys.stdin.readline())
A = [int(i) for i in sys.stdin.readline().split(' ')]

A.sort(reverse=True)
max_value = A.pop(0)
diff = deque([max_value])
ans = 0
for i in A:
    ans = ans + diff.popleft()
    diff.append(i)
    diff.append(i)

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

S, T=input(), input()
dic = {}
for i in range(len(S)):
    s, t = S[i], T[i]
    if s!=t:
        S=S.replace(s, "*")
        S=S.replace(t, s)
        S=S.replace("*", t)
    if S[:i] != T[:i]:
        print("No")
        exit()
print("Yes")


### FIXED CODE ###

S, T=input(), input()
src, trg = {}, {}
for i in range(len(S)):
    s, t = S[i], T[i]
    if (s in src and src[s] != t) or (t in trg and trg[t] != s):
        print("No")
        exit()
    src[s] = t
    trg[t] = s
print("Yes")
### BUGGY CODE ###


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

for i in range(n):
    A[i].append(1010 + i)
    for j in range(n):
        A[i][j] -= 1

#print(A)

S = [0] * n

d = 0
for ii in range(n*n*2):
    co = 0
    i = 0
    F = [0 for i in range(n)]
    ga = 0
    while co < n:
        aite = A[i][S[i]]
        #print(S)
        #print("aite",aite)
        if aite <= 1000 and A[aite][S[aite]] == i and F[i] == 0 and F[aite] == 0:
            #print("g", i, aite)
            S[i] += 1
            S[aite] += 1
            F[i] = 1
            F[aite] = 1
            co = 0
            ga += 1
        i += 1
        if i == n:
            i = 0
        co += 1
    d += 1
    #print("d", d)
    if ga == 0:
        if sum(S) == (n-1)*n:
            print(d-1)
        else:
            print(-1)
        break



### FIXED CODE ###

import sys
input = sys.stdin.readline

n = int(input())
A = [list(map(int,input().split())) for i in range(n)]
for i in range(n):
    for j in range(n-1):
        A[i][j] -= 1

AA = [[j for j in i] for i in A]

ID = [[-1] * n for i in range(n)]
id_ = 0
for i in range(n):
    for j in range(i+1,n):
        ID[i][j] = id_
        ID[j][i] = id_
        id_ += 1

for i in range(n):
    for j in range(n-1):
        A[i][j] = ID[i][A[i][j]]

M = [[] for i in range(id_)]
IN = [0] * id_
for i in range(n):
    for j in range(n-2):
        M[A[i][j]].append(A[i][j+1])
        IN[A[i][j+1]] +=1
# print(A)
# print(M)

# 以下、トポロジカルソート

S = []
s = 0

for i in range(id_):
    if IN[i] == 0:
        S.append(i)

while s < len(S):
    for x in M[S[s]]:
        IN[x] -= 1
        # print(x,IN)
        if IN[x] == 0:
            S.append(x)
    s += 1

# print(S)

if len(S) < id_:
    print(-1)
else:
    T = [1] * id_
    for i in range(id_):
        for j in M[S[i]]:
            T[j] = max(T[j], T[S[i]] + 1)
    print(max(T))


# 以下、閉路検出(今は削除)

# V = [0] * id_
# S = [0]
# V[0] = 1

# import sys

# def visit(x):
#     if V[x] == 1:
#         print(-1)
#         sys.exit()
#     elif V[x] == 0:
#         V[x] = 1
#         for i in M[x]:
#             visit(i)
#         V[x] = 2

# for i in range(id_):
#     if V[i] == 0:
#         visit(i)
# print("heironasi")

# 閉路検出ここまで
### BUGGY CODE ###

#!/usr/bin/env python3

from copy import deepcopy
from functools import lru_cache
import sys

POSS = sorted([1, 6, 36, 216, 1296, 7776, 46656, 9, 81, 729, 6561, 59049])
NMAX = 10 ** 5
# sys.setrecursionlimit(NMAX + 1)

@lru_cache(maxsize=NMAX + 1)
def dfs(n):
    assert 0 <= n <= NMAX
    res = n
    for p in reversed(POSS):
        if n - p >= 0:
            res = min(res, dfs(n - p) + 1)
    return res

def main():
    n = int(input())
    print(dfs(n))

main()


### FIXED CODE ###

#!/usr/bin/env python3

from copy import copy

POSS = [1, 6, 36, 216, 1296, 7776, 46656, 9, 81, 729, 6561, 59049]
TMAX = 20
NMAX = 100000

def do_dp(n):
    dp = [i for i in range(NMAX + 1)]
    for t in range(TMAX):
        pre = copy(dp)
        for i in range(NMAX + 1):  # 配る
            for p in POSS:
                if i + p <= NMAX:
                    dp[i + p] = min(dp[i + p], dp[i] + 1)
    return dp[n]

def main():
    n = int(input())
    print(do_dp(n))

main()
### BUGGY CODE ###

import sys
from math import factorial

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

if S[0] == 'W' or S[-1] == 'W':
    print(0)
    sys.exit()

op = "L"
for i in range(1, 2*N):
    if S[i] == S[i-1]:
        op += 'R' if op[i-1] == 'L' else 'L'
    else:
        op += 'R' if op[i-1] == 'R' else 'L'

if op.count('L') != N:
    print(0)
    sys.exit()

ct_L, ans = 0, 1

for i in op:
    if i == 'L':
        ct_L += 1
    else:
        ans *= ct_L
        ct_L -= 1

mod = 10**9+7
print(factorial(N) * ans % mod)


### FIXED CODE ###

import sys
from math import factorial

N = int(input())
S = input()
mod = 10**9+7

if S[0] == 'W' or S[-1] == 'W':
    print(0)
    sys.exit()

op = "L"
for i in range(1, 2*N):
    if S[i] == S[i-1]:
        op += 'R' if op[i-1] == 'L' else 'L'
    else:
        op += 'R' if op[i-1] == 'R' else 'L'

if op.count('L') != N:
    print(0)
    sys.exit()

ct_L, ans = 0, 1

for i in op:
    if i == 'L':
        ct_L += 1
    else:
        ans *= ct_L
        ct_L -= 1
    ans %= mod


print(factorial(N) * ans % mod)
### BUGGY CODE ###

N = int(input())
s = [input() for i in range(N)]
for i in range(N):
    s[i] = list(s[i])
    s[i].sort()
count = 0
for i in range(N):
    for j in range(i + 1, N):
        if s[i] == s[j]:
            count += 1
print(count)


### FIXED CODE ###

N = int(input())

s = []
ans = 0
count = 1

for i in range(N):
    tmp = input()
    s.append("".join(sorted(tmp)))

s.sort()

for i in range(N - 1):
    if s[i] == s[i + 1]:
        count += 1
    else:
        ans += count*(count - 1) / 2
        count = 1
ans += count*(count - 1) / 2

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

import itertools
N = int(input())
a = list(map(int, input().split()))
count = 0
b = list(itertools.combinations(range(N+1), 2))
l = len(b)
for i in range(l):
  c = b[i]
  d = c[0]
  e = c[1]
  if sum(a[d : e]) == 0:
    count += 1
print(count)

### FIXED CODE ###

from collections import Counter
N = int(input())
a = list(map(int, input().split()))
count = 0
s = list()
s.append(0)
for i in range(N):
  s.append(a[i] + s[i])
for j in  Counter(s).values():
  count += (j * (j-1))/2
print(int(count))
### BUGGY CODE ###

n,k = map(int,input().split())
a = list(map(int,input().split()))
memo = {}

for i in range(k,n):
    before = 1
    after = 1

    if not(i-1 in memo):
        for j in range(k):
            before *= a[i-j-1]
        memo[i-1] = before
    else:
        before = memo[i-1]

    if not(i in memo):
        for j in range(k):
            after *= a[i-j]
        memo[i] = after
    else:    
        after = memo[i]
        
    if after > before:
        print("Yes")
    else:
        print("No")

### FIXED CODE ###

n,k = map(int,input().split())
a = list(map(int,input().split()))
memo = {}

for i in range(k,n):
    if a[i] > a[i-k]:
        print("Yes")
    else:
        print("No")
### BUGGY CODE ###

R, G, B, N = map(int, input().split())

ans = 0
n_iter_r = N//R + 1
n_iter_g = N//G + 1

for r in range(n_iter_r):
    for g in range(n_iter_g):
        if N - R*r - G*g < 0:
            break
        else:
            if (N - R*r - G*g)%B==0:
                ans += 1

print(ans)

### FIXED CODE ###

R, G, B, N = map(int, input().split())

ans = 0
n_iter_r = N//R + 1
n_iter_g = N//G + 1

for r in range(n_iter_r):
    for g in range(n_iter_g):
        nokori = N - R*r - G*g
        if nokori < 0:
            break
        else:
            if nokori%B==0:
                ans += 1

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

import itertools

N,M,R = map(int,input().split())
r = list(map(int,input().split()))

infinit = 100000*300

distance = [[infinit]*N for _ in range(N)]

for _ in range(M):
        A,B,C = map(int,input().split())
        distance[A-1][B-1] = C
        distance[B-1][A-1] = C

for i in range(N):
        distance[i][i] = 0

for k in range(N):
        for i in range(N):
                for j in range(N):
                        distance[i][j] = min(distance[i][j],distance[i][k]+distance[k][j])


ans = infinit
for i in list(itertools.permutations(r)):
        a = 0
        for j in range(len(i)-1):
                a += distance[i[j]-1][i[j+1]-1]
        if ans > a:
                ans = a

print(ans)

### FIXED CODE ###

import sys
import itertools

def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(sys.stdin.readline()[:-1])
def IR(n): return([I() for _ in range(n)])

def main():
    N,M,R = LI()
    rs = [int(x) -1 for x in sys.stdin.readline().split()]
    D = [[10**10]*N for _ in range(N)]
    for _ in range(M):
        A,B,C = LI()
        D[A-1][B-1] = C
        D[B-1][A-1] = C
    for i in range(N):
        D[i][i] = 0

    for k in range(N):
        for i in range(N):
            for j in range(N):
                D[i][j] = min(D[i][j],D[i][k]+D[k][j])

    ans = 10**11
    for trs in itertools.permutations(rs):
        tans = 0
        for i in range(R-1):
            tans += D[trs[i]][trs[i+1]]
        ans = min(ans,tans)
    
    return(ans)

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

r , g , b , n = map(int,input().split())
ans = 0
for i in range(n+1):
    for j in range(n+1):
        if n-(r*i+g*j)>=0 and (n - (r*i+g*j)) % b ==0:
            ans += 1
print(ans)

### FIXED CODE ###

# coding: utf-8
# Your code here!
r , g , b , n = map(int,input().split())
ans = 0
R = -(-n//r)
G = -(-n//g)
for i in range(R+1):
    for j in range(G+1):
        su = n-r*i-g*j
        if n-r*i-g*j < 0:
            break
        else:
            if (su/b).is_integer():
                ans += 1
print(ans)
### BUGGY CODE ###

x,y = map(int,input().split())

if x == y:
     print('-1')
elif y == 1:
     print('-1')
else:
     i = 2 
     while True:
          if x*i % y == 0:
               i += 1     
               continue
          else:
               print(x*i)
               break 

### FIXED CODE ###

x,y = map(int,input().split())


if x%y == 0:
     print('-1')
else:
     i = 2 
     while True:
          if x*i % y == 0:
               i += 1     
               continue
          else:
               print(x*i)
               break
### BUGGY 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

  cnt=-1
  ans=0
  for x in t:
    while True:
      cnt+=1
      ans+=1
      if s[cnt%ln]==x:
        break

  return ans

# main()
print(main())


### FIXED CODE ###

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())
### BUGGY CODE ###

n,k = map(int, input().split())
al = list(map(int, input().split()))

next = [[0]*n for _ in range(60)]
for i in range(n):
    next[0][i] = al[i]-1

for p in range(1,60):
    for i in range(n):
        next[p][i] = next[p-1][next[p-1][i]]

res = 0
for p in range(59,-1,-1):
    if (k>>p)&1 == 1:
        res = next[p][res]

print(res+1)

### FIXED CODE ###

n,k = map(int, input().split())
al = [0]+list(map(int, input().split()))

s = 1
visited = [0]*(n+1)
cnt = 0
for i in range(k):
    s = al[s]
    cnt += 1
    if visited[s]>0:
        r = k - cnt
        l = cnt - visited[s]
        for _ in range(r%l):
            s = al[s]
        break
    else:
        visited[s] = cnt
print(s)
### BUGGY CODE ###

import sys
d=[]
input()
for e in sys.stdin:
 c,g=e.split()
 if'i'==c[0]:d+=[g]
 else:print(['no','yes'][g in d])


### FIXED CODE ###

import sys
def m():
 d={};input()
 for e in sys.stdin:
  if'f'==e[0]:print(['no','yes'][e[5:]in d])
  else:d[e[7:]]=0
if'__main__'==__name__:m()
### BUGGY CODE ###

#C
l, r = map(int, input().split())
ans=2018
for i in range(l, r + 1):
    for j in range(i + 1, r + 1):
        if i * j % 2019 < ans:
            ans = i * j % 2019
print(ans)

### FIXED CODE ###

#C
import sys
l, r = map(int, input().split())
ans=2018
for i in range(l, r + 1):
    for j in range(i + 1, r + 1):
        if i * j % 2019 < ans:
            ans = i * j % 2019
        if ans == 0:
            print(0)
            sys.exit()
print(ans)