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

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

ans = 0
for i in range(0, N-1):
    a = A[i]
    b = A[i+1]
    while a + b > x:
        if b > 0:
            b -= 1
            ans += 1
        elif a > 0:
            a -= 1
            ans += 1
    A[i] = a
    A[i+1] = b

print(ans)

### FIXED CODE ###

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

ans = 0
for i in range(0, N-1):
    while A[i] + A[i+1] > x:
        tmp = A[i + 1] + A[i] - x
        if A[i+1] > 0:
            if tmp > A[i+1]:
                tmp = A[i+1]
            A[i+1] -= tmp
            ans += tmp
        elif A[i] > 0:
            if tmp > A[i]:
                tmp = A[i]
            A[i] -= tmp
            ans += tmp

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

import numpy as np

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

for i in range(min(k, 50)):
    b = [0] * n
    b = np.array(b)
    for j in range(n):
        mi = max(0, j-a[j])
        ma = min(n-1, j+a[j])
        b[mi] += 1
        if ma + 1 <= n -1:
            b[ma+1] -= 1
    c = [0] * n
    s = 0
    for k in range(n):
        s += b[k]
        c[k] = s
    a = c

for i in a:
    print(i, end=' ')

### FIXED CODE ###

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

for i in range(min(k, 45)):
    b = [0] * n
    for j in range(n):
        mi = max(0, j-a[j])
        ma = min(n-1, j+a[j])
        b[mi] += 1
        if ma + 1 <= n -1:
            b[ma+1] -= 1
    c = [0] * n
    s = 0
    for k in range(n):
        s += b[k]
        c[k] = s
    a = c

for i in a:
    print(i, end=' ')
### BUGGY CODE ###

S = input()
Sr = S[::-1] # 一の位から考える

T = 0 # 部分文字列
mod = [0] * 2019 # mod数え上げ配列
mod[0] += 1 # 「部分文字列T = S」の場合の、 「0 % 2019 = 0」を予めカウント
for i, s in enumerate(Sr):
  T += int(s) * ((10 ** (i+1)) % 2019)
  mod[T%2019] += 1
  
# ペアを合計
mod = [m//2 for m in mod]
print(sum(mod))

### FIXED CODE ###

S = input()
Sr = S[::-1] # 一の位から考える

T = 0 # 部分文字列
mod = [0] * 2019 # mod数え上げ配列
mod[0] += 1 # 「部分文字列T = S」の場合の、 「0 % 2019 = 0」を予めカウント
d = 1 # 桁数
for i, s in enumerate(Sr):
  T += int(s) * d
  T %= 2019
  d = (d * 10) % 2019
  
  mod[T] += 1
  
# ペアを合計
# n個から2通り選ぶ（nC2）
mod = [n * (n-1) // 2 for n in mod]
print(sum(mod))
### BUGGY CODE ###

import collections
import copy

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

for i in range(n):
    tmp_l = copy.copy(a)
    tmp_l.pop(i)
    c = collections.Counter(tmp_l)
    tmp_ans = 0
    for v in c.values():
        tmp_ans += ((v*(v-1))//2)
#     ans.append(tmp_ans)
    print(tmp_ans)

### FIXED CODE ###

from collections import Counter

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

a_cnt = Counter(a)

x = 0
for i in a_cnt.values():
    x += i * (i - 1) // 2
    
for i in a:
    ans = x - (a_cnt[i] * (a_cnt[i] - 1) // 2)
    ans += (a_cnt[i]-1) * (a_cnt[i]-2) // 2
    print(ans)
### BUGGY CODE ###

n=int(input())
ans=0
from  itertools import product
l1=[i for i in range(1,n+1)]
l2=[i for i in range(1,n+1)]
l3=[i for i in range(1,n+1)]
p=product(l1,l2,l3)
for a,b,c in p:
    if a*b+c==n:
        ans+=1
print(ans)

### FIXED CODE ###

n=int(input())
ans=0
for i in range(1,n):
    ans+=(n-1)//i
print(ans)
### BUGGY CODE ###

import fractions
import functools

def main():
    n = int(input())
    a = [int(t)for t in input().split()]

    a_gcd = functools.reduce(fractions.gcd,a)
    gcdlist = []

    for i in range(n):
        t = [x//a_gcd for x in a]
        del t[i]
        t_gcd = functools.reduce(fractions.gcd,t)
        gcdlist.append(t_gcd)

    print(a_gcd*max(gcdlist))
    
if __name__ == "__main__":
    main()

### FIXED CODE ###

import fractions
import functools

def main():
    n = int(input())
    a = [int(t)for t in input().split()]

    a_gcd = functools.reduce(fractions.gcd,a)
    a = [x//a_gcd for x in a]
    
    a_rev = a[::-1]

    lgcd = [0]
    rgcd = [0]
    for i in range(n):
        l = fractions.gcd(a[i],lgcd[i])
        r = fractions.gcd(a_rev[i],rgcd[i])
        lgcd.append(l)
        rgcd.append(r)

    rgcd = rgcd[::-1]
    g = [fractions.gcd(lgcd[i],rgcd[i+1]) for i in range(n)]
    
    print(max(g)*a_gcd)
    
    
if __name__ == "__main__":
    main()
### BUGGY CODE ###

N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break

    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = (K // len_cycle) - 1
            score = sum_cycle * num_multiply
            for j in range(K % len_cycle + len_cycle):
                score += (scores*2)[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)

print(max_score)

### FIXED CODE ###

N, K = map(int, input().split())
Ps = list(map(int, input().split()))
Ps = [i - 1 for i in Ps]
Cs = list(map(int, input().split()))
max_score = -float("inf")


for i in range(N):
    scores = []
    idx = i  # starting index
    while True:
        idx = Ps[idx]  # point to the next index
        scores.append(Cs[idx])  # fetch a score to add
        if idx == i:  # when the cycle is closed
            break

    len_cycle = len(scores)
    sum_cycle = sum(scores)

    if sum_cycle <= 0:  # when each cycle reduces the total score
        score = 0
        for j in range(min(K, len_cycle)):
            score += scores[j]
            max_score = max(max_score, score)
    else:
        if K // len_cycle > 0:
            num_multiply = K // len_cycle - 1
            score = sum_cycle * num_multiply
            scores = scores * 2
            for j in range(K % len_cycle + len_cycle):
                score += scores[j]
                max_score = max(max_score, score)
        else:
            num_multiply = 0  # len_cycle > K
            score = sum_cycle * num_multiply
            for j in range(K):
                score += scores[j]
                max_score = max(max_score, score)

print(max_score)
### BUGGY CODE ###

import math
 
N=int(input())
 
def gcd(*numbers):
    return reduce(math.gcd, numbers)
 
A = 0
for i in range(1,N+1):
  for j in range(1,N+1):
    for k in range(1,N+1):
      A += math.gcd(math.gcd(i,j),k)

print(A)

### FIXED CODE ###

import math
 
N=int(input())
 
A = 0
for i in range(1,N+1):
  for j in range(1,N+1):
    for k in range(1,N+1):
      A += math.gcd(math.gcd(i,j),k)

print(A)
### BUGGY CODE ###

import math
H, N = tuple(map(int, input().split(" ")))
AB = []
for _ in range(N):
    AB.append(tuple(map(int, input().split(" "))))

minpower = 10 ** 8 + 1

# dp[n][h] = 0 ~ n - 1 番目の魔法を使えた時、残り体力がhのモンスターを倒すために必要な魔力
dp = [[minpower for _ in range(H + 1)] for __ in range(N)]
for h in range(H):
    dp[0][h] = math.ceil(h / AB[0][0]) * AB[0][1]

for n in range(N):
    dp[n][0] = 0

for h in range(H + 1):
    for n in range(N):
        a, b = AB[n]

        if h - a < 0:
            dp[n][h] = min(
                dp[n-1][h],
                b
            )
        else:
            dp[n][h] = min(
                dp[n-1][h],
                dp[n][h-a] + b)
print(dp[-1][H])

### FIXED CODE ###

import math
H, N = tuple(map(int, input().split(" ")))
AB = []
for _ in range(N):
    AB.append(tuple(map(int, input().split(" "))))

minpower = 10 ** 8 + 1

# dp[n][h] = 0 ~ n - 1 番目の魔法を使えた時、残り体力がhのモンスターを倒すために必要な魔力
dp = [[minpower for _ in range(H + 1)] for __ in range(N)]
for h in range(H):
    dp[0][h] = math.ceil(h / AB[0][0]) * AB[0][1]

for n in range(N):
    dp[n][0] = 0

for h in range(H + 1):
    for n in range(N):
        a, b = AB[n]

        if h - a < 0:
            dp[n][h] = min(
                dp[n-1][h],
                b
            )
        else:
            dp[n][h] = min(
                dp[n-1][h],
                dp[n][h-a] + b)
print(dp[-1][H])
### BUGGY CODE ###

N,Q = list(map(int, input().split()))
S = list(input())
l = []
r = []
for _ in range(Q):
    L,R = list(map(int, input().split()))
    l.append(L)
    r.append(R)
flag = False
ac = [0]*N

for j in range(N):
        if S[j] == 'A':
            flag = True
            continue
        if S[j] == 'C' and flag:
            ac[j] += 1
        flag = False


for i in range(Q):
    print(sum(ac[l[i]:r[i]]))


### FIXED CODE ###

N,Q = list(map(int, input().split()))
S = list(input())
l = []
r = []
for _ in range(Q):
    L,R = list(map(int, input().split()))
    l.append(L)
    r.append(R)
flag = False
ac = [0]*N
count = 0

for j in range(N):
        if S[j] == 'A':
            flag = True
            ac[j] = count
            continue
        if S[j] == 'C' and flag:
            count += 1
        ac[j] = count
        flag = False


for i in range(Q):
    print(ac[r[i]-1]-ac[l[i]-1])
### BUGGY CODE ###

N = int(input())
P = list(map(int, input().split()))
ans = 0
for i in range(0,N):
    if min(P[:i+1]) == P[i]:
        ans += 1
    else:
        continue
print(ans)

### FIXED CODE ###

N = int(input())
P = list(map(int, input().split()))
ans = 0
current_min = N
for i in range(0,N):
    current_min = min(current_min, P[i])
    if current_min == P[i]:
        ans += 1
print(ans)
### BUGGY CODE ###

N, P = map(int, input().split())
S = input()
c = 0
for i in range(N):
    for j in range(i+1, N+1):
        s = S[i:j]
        c += (int(s) % P == 0)
print(c)

### FIXED CODE ###

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

if P == 2 or P == 5:
    def solve25(N, P, S):
        c = 0
        for i in range(N-1, -1, -1):
            if int(S[i]) % P == 0:
                # 以降桁を増やしてもOK
                c += i+1
        return c
    print(solve25(N, P, S))
else:
    def solve(N, P, S):
        rcounts = [0] * P
        rcounts[0] = 1 # sそのものが割り切れた場合に引き算する相手がいないから
        ints = 0
        for i, s in enumerate(S[::-1]):
            ints += int(s) * pow(10, i, P)
            r = ints % P
            rcounts[r] += 1
        c = 0
        for v in rcounts:
            c += v*(v-1)//2
        return c
    print(solve(N, P, S))
### BUGGY CODE ###

n,k = map(int, input().split())
p = list(map(int, input().split()))
ans = 0

for i in range(n-k+1):
    ans = max(ans, sum(p[i:i+k]))

print((ans+k)/2)


### FIXED CODE ###

n,k = map(int, input().split())
p = list(map(int, input().split()))
ans = 0

for i in range(n-k+1):
    if i==0:
        t=sum(p[0:k])
    else:
        t=t-p[i-1]+p[i+k-1]
    ans=max(ans,t)

print((ans+k)/2)
### BUGGY CODE ###

S = input()
s = len(S)
shift = 10**100
K = shift.bit_length()

def db(A:list, k:int):
    dv = [[0]*s for _ in range(k+1)]
    dv[0] = A
    for kk in range(1,k+1):
        for n in range(s):
            dv[kk][n] = dv[kk-1][dv[kk-1][n]]
    return dv[k]

a = [1+n if i == "R" else n-1 for n,i in enumerate(S)]


for i in range(1,K):
    if (shift >> i)&1:
        a = db(a, i)
ans = [0]*s
for j in a:
    ans[j]+=1
print(*ans)

### FIXED CODE ###

LOG = 18

def main():
    S = input()
    N = len(S)
    to = []
    for _ in range(LOG):
        l = [0]*N
        to.append(l)
        
    for i in range(N):
        to[0][i] = i + 1 if S[i] == "R" else i -1
    
    for i in range(1, LOG):
        for j in range(N):
            to[i][j] = to[i-1][to[i-1][j]]
            
    ans = [0]*N
    for j in range(N):
        ans[to[LOG-1][j]] += 1
        
    print(*ans)
    return

main()
### BUGGY CODE ###

n,m = map(int, input().split())
LR = [list(map(int, input().split())) for i in range(m)]
ANS = []
for i in range(m):
  ANS.append(list(range(LR[i][0],LR[i][1]+1)))
  
def f(A,B):
  if set(A)&set(B) == set():
    print(0)
    exit()
  else:
    return(list(set(A)&set(B)))
X = ANS[0]
for i in range(1,m):
  X = f(X,ANS[i])

print(len(X))

### FIXED CODE ###

n,m = map(int, input().split())
LR = [list(map(int, input().split())) for i in range(m)]
X = [LR[i][0] for i in range(m)]
Y = [LR[i][1] for i in range(m)]

print(max(min(Y)-max(X)+1,0))
### BUGGY CODE ###

# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
import numpy as np
N, K = map(int, raw_input().split())

def test():
    ia, ib = map(int, raw_input().split())
    return np.ones(ib) * ia

R = np.array([_ for i in xrange(N) for _ in test()])
print int(np.sort(R)[K-1])

### FIXED CODE ###

# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
N, K = map(int, raw_input().split())
R = [0] * (10**5+10) 

for i in xrange(N):
     ia, ib = map(int, raw_input().split())
     R[ia] += ib

k = 0
c = 0
while k < K:
    c += 1
    k += R[c]
print c
### BUGGY CODE ###

N,K=map(int,input().split())
An = list(map(int,input().split()))
if K==0:
  print(sum(An))
else:
  def f(X, An):
    rtn=0
    for Ai in An:
      rtn += (X^Ai)
    return rtn

  tmp = sum(An)
  for i in range(1,K+1):
    fx = f(i,An)
    if tmp < fx:
      tmp = fx
  print(tmp)
 

### FIXED CODE ###

N,K = map(int,input().split())
An = list(map(int,input().split()))

rtn=0
bit_max = 40
for s in range(bit_max, -1, -1):
  target = 1 << s
  numof_hit = len([1 for a in An if a & target != 0])
  
  if target<=K and numof_hit < N-numof_hit:
    numof_hit = N-numof_hit
    K -= target
  
  rtn += target * numof_hit

print(rtn)
### BUGGY CODE ###

import sys

def merge(A, left, mid, right, num_compare):
	n1 = mid - left
	n2 = right - mid

	L = [0 for i in range(n1)]
	R = [0 for i in range(n2)]

	for i in range(n1):
		L[i] = A[left + i]

	for i in range(n2):
		R[i] = A[mid + i]
	
	i = 0
	j = 0

	num_compare += right - left
	for k in range(left, right):
		if j >= n2:
			A[k] = L[i]
			i += 1
		elif i < n1 and L[i] <= R[j]:
			A[k] = L[i]
			i += 1
		else:
			A[k] = R[j]
			j += 1
	return num_compare

def merge_sort(A, left, right, num_compare):
	if left + 1 < right:
		mid = (left + right) // 2
		num_compare = merge_sort(A, left, mid, num_compare)
		num_compare = merge_sort(A, mid, right, num_compare)
		num_compare = merge(A, left, mid, right, num_compare)

	return num_compare


#fin = open("test.txt", "r")
fin = sys.stdin



n = int(fin.readline())
S = list(map(int, fin.readline().split()))

num_compare = 0
num_compare = merge_sort(S, 0, n, num_compare)

print(S[0], end = "")
for s in S[1:]:
	print(" " + str(s), end = "")
print("") 
print(num_compare)

### FIXED CODE ###

import sys

def merge(A, left, mid, right, num_compare):
	n1 = mid - left
	n2 = right - mid

	L = A[left:mid] + [SENTINEL]
	R = A[mid:right] + [SENTINEL]
	
	i = 0
	j = 0

	num_compare += right - left
	for k in range(left, right):
		if L[i] <= R[j]:
			A[k] = L[i]
			i += 1
		else:
			A[k] = R[j]
			j += 1
	return num_compare

def merge_sort(A, left, right, num_compare):
	if left + 1 < right:
		mid = (left + right) // 2
		num_compare = merge_sort(A, left, mid, num_compare)
		num_compare = merge_sort(A, mid, right, num_compare)
		num_compare = merge(A, left, mid, right, num_compare)

	return num_compare


#fin = open("test.txt", "r")
fin = sys.stdin

SENTINEL = float("inf")

n = int(fin.readline())
S = list(map(int, fin.readline().split()))

num_compare = 0
num_compare = merge_sort(S, 0, n, num_compare)

print(S[0], end = "")
for s in S[1:]:
	print(" " + str(s), end = "")
print("") 
print(num_compare)
### BUGGY CODE ###

import numpy as np

N, Ma, Mb = map(int, input().split())
l = []
for i in range(N):
    l.append(list(map(int, input().split())))
ans = np.inf

dp = np.full((N + 1, 10 * N + 1, 10 * N + 1), np.inf)
dp[0][0][0] = 0
for n in range(N):
    for a in range(10 * N):
        for b in range(10 * N):
            if dp[n][a][b] == np.inf:
                continue
            dp[n + 1][a][b] = min(dp[n + 1][a][b], dp[n][a][b])
            dp[n + 1][a + l[n][0]][b + l[n][1]] = min(dp[n + 1][a + l[n][0]][b + l[n][1]], dp[n][a][b] + l[n][2])
# np.set_printoptions(threshold=np.inf)
# print(dp)
for a in range(1, 10 * N):
    for b in range(1, 10 * N):
        if a * Mb == b * Ma:
            ans = min(ans, dp[n + 1][a][b])
if ans == np.inf:
    print(-1)
else:
    print(int(ans))

### FIXED CODE ###

N, Ma, Mb = map(int, input().split())
l = []
for i in range(N):
    l.append(list(map(int, input().split())))
ans = float('inf')

Mab = 10 * N + 1
dp = [[[float('inf')] * Mab for _ in range(Mab)] for _ in range(N + 1)]
dp[0][0][0] = 0
for n in range(N):
    for a in range(10 * N):
        for b in range(10 * N):
            if dp[n][a][b] == float('inf'):
                continue
            dp[n + 1][a][b] = min(dp[n + 1][a][b], dp[n][a][b])
            dp[n + 1][a + l[n][0]][b + l[n][1]] = min(dp[n + 1][a + l[n][0]][b + l[n][1]], dp[n][a][b] + l[n][2])
# np.set_printoptions(threshold=np.inf)
# print(dp)
for a in range(1, 10 * N):
    for b in range(1, 10 * N):
        if a * Mb == b * Ma:
            ans = min(ans, dp[n + 1][a][b])
if ans == float('inf'):
    print(-1)
else:
    print(int(ans))
### BUGGY CODE ###

import math
import itertools
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd, numbers)

k = int(input())

ans = 0 

for a,b,c in itertools.product(range(1,k + 1), repeat=3):
    s = gcd(a,b,c)
    ans += s
print(ans)

### FIXED CODE ###

import math
 
k = int(input()) + 1
ans = 0
 
for a in range(1, k):
    for b in range(1, k):
        d = math.gcd(a, b)
        for c in range(1, k):
            ans += math.gcd(d, c)
 
print(ans)
### BUGGY CODE ###

import sys

N=int(input())
amat=[[-1]]
for i in range(N):
  alist=list(map(int,input().split()))
  amat.append(list(reversed(alist)))
  
#print(amat)
answer=0
matched_flag=[False]*(N+1)
while(True):  
  answer+=1
  matched_flag=[False]*(N+1)
  unchanged=True
  
  for i in range(1,N+1):
    if len(amat[i]) == 0 or matched_flag[i]:
      continue
      
    ai_next = amat[i][-1]
    if amat[ai_next][-1]==i and not matched_flag[ai_next]:
      #print(i,ai_next,answer)
      amat[i].pop()
      amat[ai_next].pop()
      matched_flag[i]=True
      matched_flag[ai_next]=True
      unchanged=False
  
  if unchanged:
    print(-1)
    sys.exit()
  else:
    maxlist=-1
    for i in range(1,N+1):
      maxlist=max(maxlist,len(amat[i]))
    if maxlist==0:
      print(answer)
      sys.exit()
      


### FIXED CODE ###

import sys

N=int(input())
amat=[[-1]]
for i in range(N):
  alist=list(map(int,input().split()))
  amat.append(list(reversed(alist)))
  
#print(amat)
answer=0
matched_flag=[False]*(N+1)
for answer in range(1,N**3):
  if N>900 and answer>3000:
    print(N*(N-1)//2)
    sys.exit()
  
  matched_flag=[False]*(N+1)
  unchanged=True
  
  for i in range(1,N+1):
    if matched_flag[i] or len(amat[i]) == 0:
      continue
      
    ai_next = amat[i][-1]
    if amat[ai_next][-1]==i and not matched_flag[ai_next]:
      #print(i,ai_next,answer)
      matched_flag[amat[i].pop()]=True
      matched_flag[amat[ai_next].pop()]=True
      unchanged=False
  
  if unchanged:
    print(-1)
    sys.exit()
  else:
    for i in range(1,N+1):
      if len(amat[i])>0:
        break
    else:
      print(answer)
      sys.exit()
### BUGGY CODE ###


import sys

from math import *
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    n = int(input_raw[0])
    input_raw = list(read_func().strip().split())
    b_list = []
    is_last_first = False
    for i in range(n):
        is_last_first = not(is_last_first)
        if is_last_first == True:
            b_list.append((input_raw[i]))
        else:
            b_list.insert(0, (input_raw[i]))

    if is_last_first == True:
        b_list.reverse()
    print " ".join(b_list)


if __name__ == '__main__':
    main()


### FIXED CODE ###

import sys
from collections import deque

from math import *
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    n = int(input_raw[0])
    input_raw = list(read_func().strip().split())
    b_list = deque([])
    is_last_first = False
    for i in range(n):
        is_last_first = not(is_last_first)
        if is_last_first == True:
            b_list.append((input_raw[i]))
        else:
            b_list.appendleft(input_raw[i])

    if is_last_first == True:
        b_list.reverse()
    print " ".join(b_list)


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

S = input()
Q = int(input())
ans = S
for i in range(Q):
    Query = input()
    if Query[0] == "1":
        ans = ans[::-1]
    elif Query[0:3] == "2 1":
        ans = Query[4]+ans
    elif Query[0:3] == "2 2":
        ans += Query[4]
#     print(ans)
print(ans)

### FIXED CODE ###

S = input()
Q = int(input())
ans = S
## vector が1なら正方向、-1なら逆方向
vector = 1
before = ""
after = ""
for i in range(Q):
    Query = input()
    if Query[0] == "1":
        vector *= -1
    elif vector == 1 and Query[0:3] == "2 1":
        before = Query[4] + before
    elif vector == 1 and Query[0:3] == "2 2":
        after = after + Query[4]
    elif vector == -1 and Query[0:3] == "2 1":
        after = after + Query[4]
    elif vector == -1 and Query[0:3] == "2 2":
        before = Query[4] + before
#     print(before)
#     print(after)
if vector==1:
    print(before + S + after)
else:
    print(after[::-1]+S[::-1]+before[::-1])
### BUGGY CODE ###

x, k, d = map(int, input().split())
x = abs(x)
count = 0

if x - k*d > 0:
    print(x - k*d)

elif x - k*d == 0:
    print(0)

else:
    while x > 0:
        x -= d
        count += 1
    
    if (k - count) % 2 == 0:
        print(abs(x))
    
    else:
        print(x + d)

### FIXED CODE ###

x, k, d = map(int, input().split())
x = abs(x)
count = 0

if x - k*d > 0:
    print(x - k*d)

elif x - k*d == 0:
    print(0)

else:
    count = x//d + 1
    x -= count * d
    
    if (k - count) % 2 == 0:
        print(abs(x))
    
    else:
        print(x + d)
### BUGGY CODE ###

import fractions
from functools import reduce

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)

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

    ans = 1
    for i in range(n):
        tmp = num_list[i]
        num_list[i] = max(num_list)
        ans = max(ans, gcd_list(num_list))
        num_list[i] = tmp

    print(ans)

if __name__ == '__main__':
    main()

### FIXED CODE ###

import fractions

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)

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

    left = [0] * (n + 1)
    right = [0] * (n + 1)
    for i in range(n):
        left[i + 1] = (fractions.gcd(left[i],num_list[i]))
        right[n - i - 1] = (fractions.gcd(right[n - i],num_list[n - 1 - i]))
    
    ans = 0
    for i in range(n):
        ans = max(ans,fractions.gcd(left[i],right[i + 1]))

    print(ans)

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

from collections import Counter
n = int(input())
s = [tuple(sorted(list(input()))) for _ in range(n)]
ans = 0
st = []
count = {}

for i in range(n):
    if not s[i] in st:
        st += [s[i]]
        count[s[i]] = 0

for i in range(n):
    if s[i] in st:
        ans += count[s[i]]
        count[s[i]] += 1
print(ans)

### FIXED CODE ###

from collections import Counter
n = int(input())
s = [tuple(sorted(input())) for _ in range(n)]

c = Counter(s)
ans = 0
for i in c.values():
    ans += i*(i-1)//2
print(ans)