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

n, m, k = map(int, input().split())
a = list(map(int,input().split()))
b = list(map(int, input().split()))
 
ans_list = []
ans_list.append(0)

sum_a = 0
for i in range(len(a)):
  sum_a += a[i]
  sum_b = 0
  if sum_a > k:
    break
  if sum_a == k:
    temp = i+1
    ans_list.append(temp)
    break
  for j in range(len(b)):
    sum_b += b[j]
    if max(ans_list) > i+1+j:
      pass
    else:
      if (sum_a + sum_b) > k:
        temp = i+1+j
        ans_list.append(temp)
        break
      if (sum_a + sum_b) == k:
        temp = i+1+j+1
        ans_list.append(temp)
        break
      
sum_b = 0
for i in range(len(b)):
  sum_b += b[i]
  sum_a = 0
  if sum_b > k:
    break
  if sum_b == k:
    temp = i+1
    ans_list.append(temp)
    break
  for j in range(len(a)):
    sum_a += a[j]    
    if max(ans_list) > i+1+j:
      pass
    else:
      if (sum_b + sum_a) > k:
        temp = i+1+j
        ans_list.append(temp)
        break
      if (sum_b + sum_a) == k:
        temp = i+1+j+1
        ans_list.append(temp)
        break
      
print(max(ans_list))

### FIXED CODE ###

N, M, K = map(int, input().split())
A = list(map(int,input().split()))
B = list(map(int, input().split()))
a = [0]
b = [0]

ans = 0
j = M

for i in range(N):
  a.append(a[i] + A[i])

for i in range(M):
  b.append(b[i] + B[i])

for i in range(N+1):
  if a[i] > K:
    break
  while a[i] + b[j] > K:
    j -= 1
  ans = max(ans, i+j)

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

N = int(input())
count = 0
res = []

for i in range(1,N) :
    for j in range(1,N) :
        a = i
        b = j
        c = N-a*b
        
        if a*b>=N :
            break
        
        if a*b+c == N :
            count += 1

print(count)

### FIXED CODE ###

N = int(input())
count = 0

for i in range(1,N) :
    count += (N-1)//i

print(count)
### BUGGY CODE ###

def main():
    ans = 1
    for a in A:
        ans *= a
    if ans <= 10**18:
        print(ans)
    else:
        print(-1)


if __name__ == "__main__":
    N = int(input())
    A = [int(a) for a in input().split()]
    main()


### FIXED CODE ###

def main():
    if A.count(0) >= 1:
        print(0)
        return
    ans = 1
    for a in A:
        ans *= a
        if ans > L:
            print(-1)
            return
    print(ans)


if __name__ == "__main__":
    N = int(input())
    A = [int(a) for a in input().split()]
    L = 10**18
    main()
### BUGGY CODE ###

import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n = inp()
a_origin = sorted(inpl())
ans = 0
count = collections.defaultdict(int)
a = []
for i in range(n):
    count[a_origin[i]] += 1
    if count[a_origin[i]] < 3:
        a.append(a_origin[i])
n = len(a)


class Cell:
    def __init__(self, value):
        self.value = value
        self.prev = None
        self.next = None


prev = Cell(a[0])
now = prev
for i in range(1, n):
    new = Cell(a[i])
    prev.next = new
    new.prev = prev
    prev = prev.next
FLAG = True
while now:
    if not now.next:
        if FLAG:
            ans += 1
        break
    target = now.next
    FLAG = True
    while target:
        if FLAG and target.value == now.value:
            FLAG = False
            ans -= 1
        if target.value % now.value == 0:
            if target.next:
                target.next.prev = target.prev
                target.prev.next = target.next
            else:
                target.prev.next = None
        target = target.next
    ans += 1
    now = now.next
print(ans)


### FIXED CODE ###

import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n = inp()
a = sorted(inpl())
cnt = collections.Counter(a)
ans = 0
dp = [0] * (10**6 + 1)
for i in a:
    if dp[i] == 0:
        for j in range(1, 10**7):
            if i * j > 10**6:
                break
            dp[i * j] = 1
        if cnt[i] == 1:
            ans += 1
print(ans)
### BUGGY CODE ###

import collections

n=int(input())
l=[]
for _ in range(n):
    l.append(input())

c=collections.Counter(l)
cc=sorted(c.most_common())
ccc=[]
for j in cc:
    if j[1]==max(c.values()):
        ccc.append(j[0])

for k in sorted(ccc):
    print(k)

### FIXED CODE ###

import collections

n=int(input())
l=[]
for _ in range(n):
    l.append(input())

c=collections.Counter(l)
cc=c.most_common()
ccc=[]
for j in cc:
    if j[1]==cc[0][1]:
        ccc.append(j[0])

for k in sorted(ccc):
    print(k)
### BUGGY CODE ###

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

number = 0
MOD = 1000000007

for i in range(N-1):
    for j in range(i+1, N):
#        print(A[i], A[j])
        number += A[i]*A[j]


if number > MOD:
    print(number%MOD)
else:
    print(number)


### FIXED CODE ###

#!/usr/bin/env python3
import sys
from itertools import accumulate
MOD = 1000000007  # type: int


def solve(N: int, A: "List[int]"):
    aa = list(accumulate(A))
    #print(aa)
    x = sum(A)
    #print(x)

    ans = 0

    for i in range(N):
        ans += A[i]*(aa[N-1]-aa[i])%MOD
        ans %= MOD
    return print(ans)


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

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

N=int(input())
S=input()
ans=0
for i in range(N-2):
  for j in range(i+1,N-1):
    for k in range(j+1,N):
      if j-i!=k-j:
        if S[i]!=S[j] and S[j]!=S[k] and S[i]!=S[k]:
          ans+=1
print(ans)

### FIXED CODE ###

import math
N=int(input())
S=input()
ans=0
R=[]
G=[]
B=[]
for i,s in enumerate(S):
  if s=="R":
    R.append(i)
  elif s=="G":
    G.append(i)
  else:
    B.append(i)
ans=len(R)*len(G)*len(B)

for r in R:
  for g in G:
    if (r+g)%2==0:
      if S[(r+g)//2]=="B":
        ans-=1
    
for r in R:
  for b in B:
    if(r+b)%2==0:
      if S[(r+b)//2]=="G":
        ans-=1
    
for g in G:
  for b in B:
    if (g+b)%2==0:
      if S[(g+b)//2]=="R":
        ans-=1
    
print(ans)
### BUGGY CODE ###

H, W = list(map(int, input().split()))

start = []
c = []
for y in range(H):
    c.append(input())
    for x in range(W):
        if c[-1][x]=='#':
            start.append([y,x])
            
visited = [0 for _ in range(W*H)]
cnt = 0
while sum(visited)!=W*H:
    tmp_s = []
    for one in start:
        cy,cx = one
        for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            ny, nx = cy+dy, cx+dx
            if 0 <= nx < W and 0 <= ny < H and visited[ny*W+nx]==0:
                visited[ny*W+nx] = 1
                tmp_s.append([ny,nx])
    cnt+=1
    start = tmp_s
print(cnt)  

### FIXED CODE ###

def main():
    H, W = list(map(int, input().split()))
    c = [input() for j in range(H)]
    from collections import deque
    que = deque()
    dist = [[-1]*W for i in range(H)]
    for h in range(H):
        for w in range(W):
            if c[h][w] == "#":
                que.append((h, w))
                dist[h][w] = 0
 
    def bfs():
        d = ((1, 0), (0, 1), (-1, 0), (0, -1))
        while que:
            # popleftにすれば、手の短い方が優先されているので、それで訪れられる所は全て確定でいい。
            # 探索するところが無くなるまで続ける。
            cy, cx = que.popleft()
            for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                ny, nx = cy+dy, cx+dx
                if 0 <= ny < H and 0 <= nx < W and dist[ny][nx] == -1 and c[ny][nx] == '.':
                    dist[ny][nx] = dist[cy][cx] + 1
                    que.append((ny, nx))
 
    bfs()
    ans = 0
    for h in range(H):
        for w in range(W):
            ans = max(ans, dist[h][w])
    print(ans)
 
 
if __name__ == '__main__':
    main()
### BUGGY CODE ###

from collections import Counter
n, m = map(int, input().split())
l = []
a0 = 0
for i in range(m):
    a = int(input())
    if a - a0 == 0:
        print(0)
        exit()
    l.append(a - a0 - 1)
    a0 = a + 1
l.append(n - a0)
d = Counter(l)
key = list(d.keys())

def cmb(n, r):
    if r > n//2:
        r = n - r
    val = 1
    for i in range(r):
        val *= n - i
        val //= i + 1
    return val

ans = 1
for k in key:
    val = 0
    for i in range(k//2 + 1):
        val += cmb(k - i, i)
        val %= 10**9 + 7
    ans *= val**d[k]
    ans %= 10**9 + 7
print(ans)

### FIXED CODE ###

from collections import Counter
n, m = map(int, input().split())
l = []
a0 = 0
for i in range(m):
    a = int(input())
    if a - a0 == 0:
        print(0)
        exit()
    l.append(a - a0 - 1)
    a0 = a + 1
l.append(n - a0)
d = Counter(l)
key = list(d.keys())

ma = max(key)
fib = [1]*(ma + 1)
for i in range(2, ma + 1):
    fib[i] = fib[i - 2] + fib[i - 1]

ans = 1
for k in key:
    ans *= fib[k]**d[k]
    ans %= 10**9 + 7

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

import bisect

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

a.sort()

for i in range(m):
  bisect.insort(a, int(a.pop() / 2))
      
print(sum(a))

### FIXED CODE ###

import heapq

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

def minus_int(x):
  return -1 * int(x)

a = list(map(minus_int, input().split()))
heapq.heapify(a)

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

from collections import deque
n,m=map(int,input().split())
a=sorted(deque(map(int,input().split())),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=list(map(int,input().split()))
a = list(map(lambda x: x*(-1), a))
heapq.heapify(a)
for i in range(m):
  s=heapq.heappop(a)*(-1)
  heapq.heappush(a, (s//2)*(-1))

print(sum(a)*(-1))
### BUGGY CODE ###

N = int(input())
Ali = list(map(int,input().split()))
L = sorted(Ali)
li = []
[li.append(Ali.index(L[i])+1) for i in range(N)]

print(' '.join(map(str, li)))


### FIXED CODE ###

from collections import defaultdict
d = defaultdict(int)
N = int(input())
A = list(map(int, input().split()))
for i, v in enumerate(A):
    d[i + 1] = v
ans = []
d_swap = {v: k for k, v in d.items()}
sd = sorted(d_swap.items())
for i, v in enumerate(sd):
    ans.append(v[1])
print(' '.join(map(str, ans)))
### BUGGY CODE ###

def main():
    N = int(input())

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

    ans = p % (10 ** 9 + 7)
    print(ans)

if __name__ == '__main__':
    main()


### FIXED CODE ###

def main():
    N = int(input())

    p = 1
    for i in range(1, N + 1):
        # TLE
        # p *= i
        p = (p * i) % (10 ** 9 + 7)

    ans = p % (10 ** 9 + 7)
    print(ans)

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

from collections import Counter
h, w, n = [int(i) for i in input().split()]
cnt = Counter()

vs = []
for i in range(-1, 2):
	for j in range(-1, 2):
		vs.append((i,j))

for _ in range(n):
	a, b = [int(i) for i in input().split()]
	for v in vs:
		aa = a + v[0]
		bb = b + v[1]
		if 2<=aa<=h-1 and 2<=bb<=w-1:
			cnt.update([(aa, bb)])


cnt2 = [0] * 10
cnt2[0] = (h-2)*(w-2)
for k in cnt:
	c = cnt[k]
	cnt2[c] += 1
	cnt2[0] -= 1

for i in cnt2:
	print(i)





### FIXED CODE ###

from collections import Counter
h, w, n = [int(i) for i in input().split()]

vs = []
for i in range(-1, 2):
	for j in range(-1, 2):
		vs.append((i,j))
cnt = []
for _ in range(n):
	a, b = [int(i) for i in input().split()]
	for v in vs:
		aa = a + v[0]
		bb = b + v[1]
		if 2<=aa<=(h-1) and 2<=bb<=(w-1):
			cnt.append(aa*w+bb)

cnt = Counter(cnt)


cnt2 = [0] * 10
cnt2[0] = (h-2)*(w-2)
for k in cnt:
	c = cnt[k]
	cnt2[c] += 1
	cnt2[0] -= 1

for i in cnt2:
	print(i)
### BUGGY CODE ###

from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m = inpl()
a = sorted(inpl(), reverse = True)
b = [0,2,5,5,4,5,6,3,7,6]
dp = [['0']*(n+1) for _ in range(m+1)]

for i,x in enumerate(a):
    for c in range(b[x],n+1,b[x]):
        va = str(x) * (c//b[x])
        # print(c,va)
        for j in range(n+1):
            if j != 0 and (j % c == 0 or (j >= c and dp[i+1][j-c] != '0')):
                dp[i+1][j] = max(int(dp[i][j]),int(dp[i+1][j]), int(dp[i+1][j-c] + va))
                dp[i+1][j] = str(dp[i+1][j])
                continue
            dp[i+1][j] = max(int(dp[i+1][j]), int(dp[i][j]))
            dp[i+1][j] = str(dp[i+1][j])
print(dp[-1][-1])

### FIXED CODE ###

from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m = inpl()
a = sorted(inpl(), reverse = True)
b = [0,2,5,5,4,5,6,3,7,6]
dp = [0] * (n+1)

for i in a:
    w,v = b[i],i
    for j in range(n+1):
        if j < w:
            continue
        if j%w == 0 or dp[j-w]:
            dp[j] = max(dp[j], dp[j-w]*10 + v)
    # print(dp)
print(dp[-1])
### BUGGY CODE ###

import numpy as np
import itertools
n = int(input())
l = np.ones(n)
ixy = []
for i in range(n):
    a = int(input())
    for j in range(a):
        x,y = map(int, input().split())
        ixy.append([i,x-1,y])

ans = 0
ixy = np.array(ixy)
p = itertools.product([True,False], repeat=n)
for p_i in p:
    f = True
    for i,x,y in ixy:
        if not p_i[i]:
            continue
        else:
            if p_i[x] != y:
                f = False
    if f:
        ans = max(sum(p_i), ans)
print(ans)

### FIXED CODE ###

import numpy as np
import itertools
n = int(input())
ixy = []
for i in range(n):
    a = int(input())
    for j in range(a):
        x,y = map(int, input().split())
        ixy.append([i,x-1,y])

ans = 0
ixy = np.array(ixy)
p = itertools.product([True,False], repeat=n)
for p_i in p:
    f = True
    for i,x,y in ixy:
        if not p_i[i]:
            continue
        else:
            if p_i[x] != y:
                f = False
                break
    if f:
        ans = max(sum(p_i), ans)
print(ans)
### BUGGY CODE ###

k = int(input())
a = list(map(int, input().split()))
def solve():

    if a[k-1] != 2:
        print(-1)
        return

    mi = 2
    mx = 2

    for i in range(k):
        j = k-i-1

        mx = mx + a[j] - 1

        if j == 0:
            pass
        else:
            na = a[j-1]
            # if mx < na:
            #     print(-1)
            #     return
            chk = False
            for c in range(mi, mx+1):
                if c % na == 0:
                    chk = True
                    break
            if chk == False:
                print(-1)
                return

            if mi%na != 0:
                mi = mi + (na - mi%na)

            if mx%na != 0:
                mx = mx - (mx % na)

    print(mi, mx)
solve()


### FIXED CODE ###

k = int(input())
a = list(map(int, input().split()))
def solve():

    if a[k-1] != 2:
        print(-1)
        return

    mi = 2
    mx = 2

    for i in range(k):
        j = k-i-1

        mx = mx + a[j] - 1

        if j == 0:
            pass
        else:
            na = a[j-1]
            
            if mx % na != 0 and mi % na != 0 and ((mx % na) - (mi % na)) == (mx - mi):
                print(-1)
                return

            if mi%na != 0:
                mi = mi + (na - mi%na)

            if mx%na != 0:
                mx = mx - (mx % na)

    print(mi, mx)
solve()
### BUGGY CODE ###

n = int(input())
li = []
for i in range(n):
    number = int(input())
    li.append(number)
temp = []
for i in range(n):
    for j in range(len(li)):
        if i != j:
            temp.append(li[j])
        else:
            temp.append(0)
d = 0
for i in range(n):
    max_num = 0
    for j in range(n):
        if max_num<=temp[d]:
            max_num = temp[d]
        d+=1
    print(max_num)
    

### FIXED CODE ###

n = int(input())
a = []
for i in range(n):
    value = int(input())
    a.append(value)
temp = sorted(a)
max_a = temp[-1]
if len(a)>=2:
    second_a = temp[-2]
for i in range(n):
    if a[i] == max_a:
        check = i
        break
for i in range(n):
    if i == check:
        print(second_a)
    else:
        print(max_a)
### BUGGY CODE ###

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

C = [[0]*w for _ in range(h)]
for i in range(h):
    for j in range(w):
        C[i][j] = abs(A[i][j]-B[i][j])

import numpy as np
dp = [[0]*(w+1) for _ in range(h+1)]
import numpy as np
d = 80*(h*w)+1
D = 2*d+1
dp[0][0] = np.zeros(D, np.bool)
dp[0][0][C[0][0]+d] = 1
#dp[0][0][-C[0][0]+d] = 1
for i in range(h):
    for j in range(w):
        c = C[i][j]
        if i == 0 and j == 0:
            continue
        elif i == 0:
            b = np.zeros(D, np.bool)
            b[c:] |= dp[i][j-1][:D-c]
            b[:D-c] |= dp[i][j-1][c:]
        elif j == 0:
            b = np.zeros(D, np.bool)
            b[c:] |= dp[i-1][j][:D-c]
            b[:D-c] |= dp[i-1][j][c:]
        else:
            b = np.zeros(D, np.bool)
            b[c:] |= dp[i][j-1][:D-c]
            b[:D-c] |= dp[i][j-1][c:]
            b[c:] |= dp[i-1][j][:D-c]
            b[:D-c] |= dp[i-1][j][c:]
        dp[i][j] = b
#print(dp[h-1][w-1])
ans = float('inf')
for i in range(D):
    if dp[h-1][w-1][i]:
        #print(abs(i-d))
        ans = min(ans, abs(i-d))
print(ans)


### FIXED CODE ###

import numpy as np

h, w = map(int, input().split())
A = [0]*h
B = [0]*h
for _ in range(h):
  A[_] = list(map(int, input().split()))
  
for _ in range(h):
  B[_] = list(map(int, input().split()))

C = [[0]*w for _ in range(h)]
for i in range(h):
  for j in range(w):
    C[i][j] = abs(A[i][j]-B[i][j])
    
dp = [[0]*w for _ in range(h)]
D = 80 * (h + w)
L = 2*D + 1
dp[0][0] = np.zeros(L, np.bool)
dp[0][0][D+C[0][0]] = 1
for i in range(h):
  for j in range(w):
    if i == 0 and j == 0:
      continue
    x = np.zeros(L, np.bool)
    if i != 0:
      x[C[i][j]:] |= dp[i-1][j][:L-C[i][j]]
      x[:L-C[i][j]] |= dp[i-1][j][C[i][j]:]
    if j != 0:
      x[C[i][j]:] |= dp[i][j-1][:L-C[i][j]]
      x[:L-C[i][j]] |= dp[i][j-1][C[i][j]:]
    dp[i][j] = x
    
temp = np.where(dp[-1][-1]>0)[0]-D
temp = np.abs(temp)
print(np.min(temp))
### BUGGY CODE ###

import itertools
n=int(input())
d=[]
for i in range(n):
    d.append(int(input()))
r=[0]
for i in range(1,n+1):
    for j in list(itertools.combinations(d,i)):
        r.append(sum(j))
print(sorted([i for i in r if i%10!=0]+[0])[-1])

### FIXED CODE ###

data=[]
for i in range(int(input())):
    data.append(int(input()))
un=[num for num in data if num%10==0]
data=[num for num in data if num%10!=0]
if len(data)==0:
    print(0)
else:
    if sum(un+data)%10!=0:
        print(sum(un+data))
    else:
        print(sum(un+data)-min(data))
### BUGGY CODE ###

#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
import sys
import itertools
import collections

INF = 1145141919


def solve(S: int):
    l = list(reversed(str(S)))
    a = [int(l[c]) * 10**c for c in range(len(l))]

    def list_cumsum(l):
        return list(itertools.accumulate(l))
    s = [n % 2019 for n in list_cumsum([0]+a)]

    return sum([sum(range(v)) for v in collections.Counter(s).values()])


def main():

    sys.setrecursionlimit(10 ** 6)

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = int(next(tokens))  # type: int
    print(solve(S))


if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
# Generated by https://github.com/kyuridenamida/atcoder-tools
import sys
import itertools
import collections

INF = 1145141919


def solve(S: int):
    l = list(reversed(str(S)))
    a = [int(l[c]) * pow(10, c, 2019) for c in range(len(l))]

    def list_cumsum(l):
        return list(itertools.accumulate(l))
    s = [n % 2019 for n in list_cumsum([0]+a)]

    return sum([int(v * (v-1) / 2) for v in collections.Counter(s).values()])


def main():

    sys.setrecursionlimit(10 ** 6)

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = int(next(tokens))  # type: int
    print(solve(S))


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

n, k = map(int, input().split())
h = [int(x) for x in input().split()]

dp = [0]*n

dp[0] = 0
dp[1] = abs(h[1]-h[0])

for i in range(2,n):
    dp[i] = abs(h[i] - h[i-1]) + dp[i-1]
    for j in range(2,k+1):
        if i-j >= 0:
            dp[i] = min(dp[i], abs(h[i]-h[i-j])+dp[i-j])

print(dp[-1])


### FIXED CODE ###

n, k = map(int, input().split())
h = [int(x) for x in input().split()]

dp = [0]*n

dp[0] = 0
dp[1] = abs(h[1]-h[0])

for i in range(2,n):
    dp[i] = abs(h[i] - h[i-1]) + dp[i-1]
    for j in range(2,k+1):
        if i-j >= 0:
            dp[i] = min(dp[i], abs(h[i]-h[i-j])+dp[i-j])

print(dp[-1])
### BUGGY CODE ###

S = input()
N = int(input())
Q = list([_ for _ in input().split()] for _ in range(N))

def move(s, q):
    if q[0] == "1":
        return s[::-1]
    else:
        if q[1] == "1":
            return q[2] + s
        else:
            return s + q[2]
        
for q in Q:
    S = move(S, q)
print(S)

### FIXED CODE ###

S = input()
N = int(input())
Q = tuple([_ for _ in input().split()] for _ in range(N))
C = 0
F = ""
R = ""
for q in Q:
    if q[0] == "1":
        C = (C+1)%2
    else:
        if (int(q[1])+C)%2 != 0:
            F = q[2] + F
        else:
            R = R + q[2]
S = F + S + R
if C != 0:
    S = S[::-1]
print(S)