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


NK = input().split()
N = int(NK[0])
K = int(NK[1])

def function(N,K):
    pre =N
    # if N > K*10:
    #     return K-1



    while(1):    
        # print('N',N)
        N = abs(N-K)
        if pre == N:
            return pre

        if pre< N:
            return pre
        pre = N 

print(function(N,K))



### FIXED CODE ###


NK = input().split()
N = int(NK[0])
K = int(NK[1])

# N = 1000000000
# K = 1

def func(N,K):
    prev = N 

    while(1):
        N = abs(N-K)
        if prev<=N:
            return prev
        prev = N


def fun(N,K):
    N = (N % K) 
    return N  

S=fun(N,K)
T = func(S,K)
# print('S',S)
# print('T',T)
print(T)
### BUGGY CODE ###

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

for _ in range(M):
	idx = A.index(max(A))
	A[idx] //= 2
sum = 0
for a in A: sum += a
print(sum)

### FIXED CODE ###

import heapq

N, M = map(int, input().split())
A = list(map(int, input().split()))
h = []

for a in A: heapq.heappush(h, -a)
for _ in range(M):
	a = heapq.heappop(h) * -1
	a //= 2
	heapq.heappush(h, -a)

sum = 0
for _ in range(N): 
	sum -= heapq.heappop(h)
print(sum)
### BUGGY CODE ###

from sys import stdin
from collections import defaultdict, deque, Counter
import sys
from bisect import bisect_left
import heapq
import math
import numpy as np

sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

n = int(stdin.readline().rstrip())
#l = list(map(int, stdin.readline().rstrip().split()))
#A, B, C = map(int, stdin.readline().rstrip().split())
#S = [list(stdin.buffer.readline().decode().rstrip()) for _ in range(h)]

c =[]
same = []

for i in range(n):
    ci = Counter(str(stdin.readline().rstrip()))
    if ci in c:
        same[c.index(ci)] += 1
    else:
        c.append(ci)
        same.append(1)

ans = 0
for i in range(len(same)):
    ans += same[i] * (same[i] - 1) / 2

print(int(ans))


### FIXED CODE ###

from sys import stdin
from collections import defaultdict, deque, Counter
import sys
from bisect import bisect_left
import heapq
import math
#import numpy as np

sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

n = int(stdin.readline().rstrip())
#l = list(map(int, stdin.readline().rstrip().split()))
#A, B, C = map(int, stdin.readline().rstrip().split())
#S = [list(stdin.buffer.readline().decode().rstrip()) for _ in range(h)]

s = {}
ans = 0

for i in range(n):
    l = list(str(stdin.readline().rstrip()))
    l.sort()
    l = str(l)
    if l in s:
        s[l] += 1
        ans += s[l] -1
    else:
        s[l] = 1

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

import sys
from heapq import heappop, heappush
input = sys.stdin.readline
# int(input()) # 入力が1つ
n, x, y = map(int, input().split()) # 入力が複数
graph = [[] for _ in range(n)]

for i in range(n - 1):
    graph[i].append((1, i + 1))
    graph[i + 1].append((1, i))
graph[x - 1].append((1, y - 1))
graph[y - 1].append((1, x - 1))

def dijkstra(graph, n, start):
    inf = float('inf')
    visited = [inf] * n
    visited[start] = 0
    heap = [(0, start)] #(cost, vertex)
    while heap:
        _, vertex = heappop(heap)
        for c, v in graph[vertex]:
            cost = visited[vertex] + c
            if visited[v] > cost:
                visited[v] = cost
                heappush(heap, (cost, v))
    return visited

path = []
for i in range(n):
    visited = dijkstra(graph, n, i)
    path.append(visited)
    
for k in range(1, n):
    ans = 0
    for i in range(len(path)):
        visited = path[i]
        for j in range(i, len(visited)):
            if visited[j] - visited[i] == k:
                ans += 1
    print(ans)


### FIXED CODE ###

import sys
from heapq import heappop, heappush
input = sys.stdin.readline
# int(input()) # 入力が1つ
n, x, y = map(int, input().split()) # 入力が複数
graph = [[] for _ in range(n)]

for i in range(n - 1):
    graph[i].append((1, i + 1))
    graph[i + 1].append((1, i))
graph[x - 1].append((1, y - 1))
graph[y - 1].append((1, x - 1))

def dijkstra(graph, n, start):
    inf = float('inf')
    visited = [inf] * n
    visited[start] = 0
    heap = [(0, start)] #(cost, vertex)
    while heap:
        _, vertex = heappop(heap)
        for c, v in graph[vertex]:
            cost = visited[vertex] + c
            if visited[v] > cost:
                visited[v] = cost
                heappush(heap, (cost, v))
    return visited

path = []
for i in range(n):
    visited = dijkstra(graph, n, i)
    path.append(visited)

# for k in range(1, n):
#     ans = 0
#     for i in range(len(path)):
#         visited = path[i]
#         for j in range(i, len(visited)):
#             if visited[j] - visited[i] == k:
#                 ans += 1
#     print(ans)

t = [0] * n
for i in range(len(path)):
    visited = path[i]
    for j in range(i, len(visited)):
        diff = visited[j] - visited[i]
        t[diff] += 1
for k in range(1, n):
    ans = t[k]
    print(ans)
### BUGGY CODE ###

N=raw_input()
LN=raw_input().split()

n = int(N)
ln = [int(i) for i in LN]

ln.sort()

def bin_search(s,e,t):
    # return minimum i where s <= i < e and ln[i] >= t
    m = (s + e)/2
    if m == s:
        return s

    if t < ln[m]:
        return bin_search(s,m,t)
    else:
        return bin_search(m,e,t)



r = 0
for i in range(n-1, 1, -1):
    a = ln[i]
    for j in range(i-1, 0, -1):
        b = ln[j]
        c = a - b
        if ln[j-1] > c:
            idx = bin_search(0,j,c+1)
            r += j - idx
        else:
            break

print r


### FIXED CODE ###

import bisect

N=int(raw_input())
LN=map(int, raw_input().split())

LN.sort()

r = 0
for i in xrange(N-1, 1, -1):
    a = LN[i]
    for j in xrange(i-1, 0, -1):
        b = LN[j]
        if a > 2*b:
            break
        idx = bisect.bisect_left(LN, a-b+1)
        if idx < j:
            r += j - idx

print r
### BUGGY CODE ###

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

memo = [0, abs(h[1]-h[0])]
def dp(n):
  for i in range(len(memo), n+1):
    costs = [memo[i-j]+abs(h[i]-h[i-j]) for j in range(1, min(i, K)+1)]
    memo.append(min(costs))
  return memo[n]

if __name__ == '__main__':
  print(dp(N-1))

### FIXED CODE ###

N, K = map(int, input().split())
h = list(map(int, input().split()))
c = [0]*N
for i in range(1, N):
    c[i] = min([c[j] + abs(h[i]-h[j]) for j in range(max(0, i-K), i)])
print(c[N-1])
### BUGGY CODE ###

import sys
sys.setrecursionlimit(200005)

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
g = [[] for _ in range(n)]
for i in range(n-1):
    a, b = na()
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)

ps = [0] * n
for i in range(q):
    p, x = na()
    p -= 1
    ps[p] += x

ans = [0] * n

def dfs(cur, pre, curv):
    global ps, ans, g
    curv += ps[cur]
    ans[cur] = curv
    for e in g[cur]:
        if e == pre: continue
        dfs(e, cur, curv)

dfs(0, -1, 0)

print(" ".join(map(str, ans)))


### FIXED CODE ###

import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, q = na()
g = [[] for _ in range(n)]
for i in range(n-1):
    a, b = na()
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)

ps = [0] * n
for i in range(q):
    p, x = na()
    p -= 1
    ps[p] += x

stack = [0] * (n+1)
inds = [0] * (n+1)

sp = 0
stack[sp] = 0
sp += 1

while sp > 0:
    cur = stack[sp-1]
    if inds[sp-1] == len(g[cur]):
        sp -= 1
        continue
    if inds[sp-1] == 0 and sp > 1:
        ps[cur] += ps[stack[sp-2]]
    if sp == 1 or stack[sp-2] != g[cur][inds[sp-1]]:
        stack[sp] = g[cur][inds[sp-1]]
        inds[sp] = 0
        inds[sp-1] += 1
        sp += 1
        continue
    inds[sp - 1] += 1

print(" ".join(map(str, ps)))
### BUGGY CODE ###

import fractions
n=int(input())
a = list(map(int, input().split()))
ans = a[0]
for i in range(1, n):
    ans = ans * a[i] // fractions.gcd(ans, a[i])
mod=10**9+7
kai=0
for i in a:
    kai+=ans//i
    kai%=mod
print(kai)

### FIXED CODE ###

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

def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

#factorization(24) 

## [[2, 3], [3, 1]]
z=[0]*(10**6+1)
for i in l:
    if i>=2:
        re=factorization(i)
        for p in re:
            z[p[0]]=max(z[p[0]],p[1])
def extgcd(a,b):
    r = [1,0,a]
    w = [0,1,b]
    while w[2]!=1:
        q = r[2]//w[2]
        r2 = w
        w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]]
        r = r2
        w = w2
    #[x,y]
    return [w[0],w[1]]

# aの逆元(mod m)を求める。(aとmは互いに素であることが前提)
def mod_inv(a,m):
    x = extgcd(a,m)[0]
    return (m+x%m)%m
w=1
mod=10**9+7
for i in range(10**6+1):
    w*=pow(i,z[i],mod)
    w%=mod
kai=0
for i in l:
    kai+=w*mod_inv(i,mod)
    kai%=mod
print(kai)
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
dp = [[0] * n for _ in range(n)]
for i in range(n):
    dp[i][i] = a[i]

for i in range(n - 2, -1, -1):
    for j in range(i + 1, n):
        dp[i][j] = max(a[i] - dp[i + 1][j], a[j] - dp[i][j - 1])

print(dp[0][n - 1])


### FIXED CODE ###

def kukan(n, a):
    dp = [[0] * n for _ in range(n)]
    for i in range(n):
        dp[i][i] = a[i]
    for i in range(n - 2, -1, -1):
        g0 = dp[i]
        g1 = dp[i + 1]
        for j in range(i + 1, n):
            L = a[i] - g1[j]
            R = a[j] - g0[j - 1]
            dp[i][j] = L if L > R else R
    return dp[0][n - 1]


n = int(input())
a = list(map(int, input().split()))
print(kukan(n, a))
### BUGGY CODE ###

import sys
from collections import deque

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7


N, D, A = MI()
monsters = list()
for i in range(N):
    x, h = MI()
    monsters.append((x, (h + A - 1) // A))
monsters.sort()

ans = 0
for i, (x, h) in enumerate(monsters):
    if h > 0:
        ans += h
        j = i + 1
        while j < N:
            xj, hj = monsters[j]
            if xj > x + 2 * D:
                break
            monsters[j] = (xj, max(0, hj - h))
            j += 1
print(ans)

### FIXED CODE ###

import sys
from bisect import bisect_right

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7


N, D, A = MI()
monsters = list()
for i in range(N):
    x, h = MI()
    monsters.append((x, (h + A - 1) // A))
monsters.sort()

X = [x for x, h in monsters]
ub = [0] * N
for i, x in enumerate(X):
    ub[i] = bisect_right(X, x + 2 * D)

dmg = [0] * N
accum = 0
ans = 0
for i, (x, h) in enumerate(monsters):
    h = h - max(0, accum + dmg[i])
    if h > 0:
        ans += h
        dmg[i] += h
        if ub[i] < N:
            dmg[ub[i]] -= h
    accum += dmg[i]
print(ans)
### BUGGY CODE ###

import numpy as np

n,k = map(int, input().split())
H = np.array([0]+list(map(int, input().split())))
dp = np.array([float("inf")]*(n+1))
dp[0] = 0
dp[1] = 0

for i in range(1, n):
  for k_i in range(1, k+1):
    if i+k_i<=n:
      dp[i+k_i] = min(dp[i+k_i], dp[i]+abs(H[i+k_i]-H[i]))
      
print(int(dp[-1]))

### FIXED CODE ###

n,k = map(int, input().split())
H = [0]+list(map(int, input().split()))
dp = [float("inf")]*(n+1)
dp[0] = 0
dp[1] = 0

for i in range(1, n):
  for k_i in range(1, k+1):
    if i+k_i<=n:
      dp[i+k_i] = min(dp[i+k_i], dp[i]+abs(H[i+k_i]-H[i]))
      
print(dp[-1])
### BUGGY CODE ###

s = input()
q = int(input())

for i in range(q):
    t = input()
    if t == '1':
        s = s[::-1]
    else:
        _, f, c = t.split()
        if f == '1':
            s = c + s
        else:
            s = s + c
print(s)

### FIXED CODE ###

S = input()
n = int(input())

d = 1
S1 = []
S2 = []
for i in range(n):
    Q = list(input().split())
    if Q[0] == '1':
        d *= -1
    else:
        f = Q[1]
        c = Q[2]
        if f == '1':
            if d == 1:
                S1.append(c)
            else:
                S2.append(c)
        else:
            if d == 1:
                S2.append(c)
            else:
                S1.append(c)
if d == 1:
    ans = ''.join(S1[::-1]) + S + ''.join(S2)
else:
    ans = ''.join(S2[::-1]) + S[::-1] + ''.join(S1)

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

import sys
H, W = map(int, input().split())
S = [line.strip("\n") for line in sys.stdin]
transposeS = ["" for _ in range(W)]

rowRunLength = [[None] * W for _ in range(H)]
columnRunLength = [[None] * H for _ in range(W)]


for idx, elem in enumerate(S):
    previousObstacleIndex = -1

    while previousObstacleIndex != W:
        obstacleIndex = elem.find("#", previousObstacleIndex + 1)
        if obstacleIndex == -1:
            obstacleIndex = W
        else:
            rowRunLength[idx][obstacleIndex] = 0
        for lightenedIndex in range(previousObstacleIndex + 1, obstacleIndex):
            rowRunLength[idx][lightenedIndex] = obstacleIndex - previousObstacleIndex - 1
        previousObstacleIndex = obstacleIndex

for i in range(W):
    for j in range(H):
        transposeS[i] += S[j][i]

for idx, elem in enumerate(transposeS):
    previousObstacleIndex = -1

    while previousObstacleIndex != H:
        obstacleIndex = elem.find("#", previousObstacleIndex + 1)
        if obstacleIndex == -1:
            obstacleIndex = H
        else:
            columnRunLength[idx][obstacleIndex] = 0
        for lightenedIndex in range(previousObstacleIndex + 1, obstacleIndex):
            columnRunLength[idx][lightenedIndex] = obstacleIndex - previousObstacleIndex - 1
        previousObstacleIndex = obstacleIndex

ans = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            ans = max(ans, rowRunLength[i][j] + columnRunLength[j][i] - 1)

print(ans)


### FIXED CODE ###

# can't AC without numpy, Python array handling with for is SLOW
import numpy as np
H, W = map(int, input().split())
S = []
for _ in range(H):
    S.append(list(input()))
S = (np.array(S) == ".") * 1

# i行j列に置いたとき上下左右の方向それぞれに光の軌跡が何マス伸びるか(自マスを含む)
trailLeft = np.zeros((H, W), dtype=int)
trailRight = np.zeros((H, W), dtype=int)
trailUp = np.zeros((H, W), dtype=int)
trailDown = np.zeros((H, W), dtype=int)

for i in range(H):
    if i == 0:
        trailUp[i] = S[i]
        trailDown[H - i - 1] = S[H - i - 1] * 1
    else:
        trailUp[i] = (trailUp[i - 1] + 1) * S[i]
        trailDown[H - i - 1] = (trailDown[H - i] + 1) * S[H - i - 1]

for j in range(W):
    if j == 0:
        trailLeft[:, j] = S[:, j]
        trailRight[:, W - j - 1] = S[:, W - j - 1] * 1
    else:
        trailLeft[:, j] = (trailLeft[:, j - 1] + 1) * S[:, j]
        trailRight[:, W - j - 1] = (trailRight[:, W - j] + 1) * S[:, W - j - 1]

print(np.max(trailLeft + trailRight + trailUp + trailDown - 3))
### BUGGY CODE ###

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

B=[0]*p
mod=p

FACT=[1]
for i in range(1,p):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(p-1,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

def Combi(a,b):
    if 0<=b<=a:
        return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
    else:
        return 0


for i in range(p):
    if A[i]==0:
        continue

    B[0]+=1
    for j in range(p):
        B[j]=(B[j]-Combi(p-1,j)*pow(-i,p-1-j,p))%p

print(*[b%p for b in B])

    
    




### FIXED CODE ###

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

B=[0]*p

INV=[None]*p# 1/aのリストを予め作っておく.
for i in range(1,p):
    INV[i]=pow(i,p-2,p)

Combi=[None]*p# Combi[i]=nCi を表す
Combi[0]=1
for i in range(1,p):
    Combi[i]=Combi[i-1]*(p-i)*INV[i] %p


for i in range(p):
    if A[i]==0:
        continue

    B[0]+=1
    POW=1
    for j in range(p):
        B[p-1-j]=(B[p-1-j]-Combi[j]*POW)%p
        POW=POW*(-i)%p

print(*[b%p for b in B])
### BUGGY CODE ###

import sys
import copy

h, w = map(int, sys.stdin.readline().split())

maps = [list(sys.stdin.readline().rstrip()) for _ in range(h)]

tmaps = [[0] * w for _ in range(h)]

def calcdist(tmaps, start, end, h, w):
    nextlist = []
    nextlist.append(start)
    count = 1
    while True:
        nexnex = []
        for i in nextlist:
            tmaps[i[0]][i[1]] = count
            if i[0] == end[0] and i[1] == end[1]:
                return count
        for i in nextlist:
            if i[0] > 0 and tmaps[i[0] -1][i[1]] == 0:
                nexnex.append([i[0] -1, i[1]])
            if i[0] < h-1 and tmaps[i[0] +1][i[1]] == 0:
                nexnex.append([i[0] +1, i[1]])
            if i[1] > 0 and tmaps[i[0]][i[1]-1] == 0:
                nexnex.append([i[0], i[1]-1])
            if i[1] < w-1 and tmaps[i[0]][i[1]+1] == 0:
                nexnex.append([i[0], i[1]+1])
        nextlist = list(map(list, set(map(tuple, nexnex))))
        count += 1
    return count

kabe = 0

for i in range(h):
    for j in range(w):
        if maps[i][j] == '#':
            tmaps[i][j] = -1
            kabe += 1

total = 0
dist = calcdist(copy.deepcopy(tmaps),[0, 0], [h-1, w-1], h, w)

print(h*w - dist - kabe)


### FIXED CODE ###

import sys
import copy

h, w = map(int, sys.stdin.readline().split())

maps = [list(sys.stdin.readline().rstrip()) for _ in range(h)]

def calcdist(maps, start, end, h, w):
    nextlist = []
    nextlist.append(start)
    count = 1
    while True:
        nexnex = []
        for i in nextlist:
            if i[0] == end[0] and i[1] == end[1]:
                return count
            if i[0] > 0 and maps[i[0] -1][i[1]] == '.':
                maps[i[0] -1][i[1]] = '#'
                nexnex.append([i[0] -1, i[1]])
            if i[0] < h-1 and maps[i[0] +1][i[1]] == '.':
                maps[i[0] +1][i[1]] = '#'
                nexnex.append([i[0] +1, i[1]])
            if i[1] > 0 and maps[i[0]][i[1]-1] == '.':
                maps[i[0]][i[1]-1] = '#'
                nexnex.append([i[0], i[1]-1])
            if i[1] < w-1 and maps[i[0]][i[1]+1] == '.':
                maps[i[0]][i[1]+1] = '#'
                nexnex.append([i[0], i[1]+1])
        nextlist = nexnex
        count += 1
        if len(nexnex) == 0:
            return -1
    return count

kabe = 0

for i in range(h):
    for j in range(w):
        if maps[i][j] == '#':
            kabe += 1

total = 0
dist = calcdist(maps,[0, 0], [h-1, w-1], h, w)
if dist == -1:
    print(-1)
else:
    print(h*w - dist - kabe)
### BUGGY CODE ###

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

ans = 0
for i in range(n-2):
  for j in range(i+1,n-1):
    for k in range(j+1,n):
      if l[k] < l[i]+l[j] and l[j] < l[i]+l[k] and l[i] < l[k]+l[j]:
        ans += 1
print(ans)

### FIXED CODE ###

from bisect import bisect_left#(sorted_list,x)で昇順ソート位置

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

l.sort()
ans = 0
for i in range(n-2):
  for j in range(i+1,n-1):
    s = l[i]+l[j]
    ans += bisect_left(l,s,j+1)-j-1
print(ans)
### BUGGY CODE ###

N, M = map(int, input().split())
G = [[] for _ in range(3 * N)]
L = [-3 for _ in range(3 * N)]
for _ in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    G[3*u+0].append(3*v+1)
    G[3*u+1].append(3*v+2)
    G[3*u+2].append(3*v+0)
s, t = map(int, input().split())
S = 3 * (s-1)
T = 3 * (t-1)

L[S] = 0
Frontier = [S]
while Frontier:
    v = Frontier.pop(0)
    for i in G[v]:
        if L[i] < 0:
            Frontier.append(i)
            L[i] = L[v] + 1

print(L[T]//3)

### FIXED CODE ###

N, M = map(int, input().split())
G = [[] for _ in range(3 * N)]
L = [-3 for _ in range(3 * N)]
for _ in range(M):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    G[3*u+0].append(3*v+1)
    G[3*u+1].append(3*v+2)
    G[3*u+2].append(3*v+0)
s, t = map(int, input().split())
S = 3 * (s-1)
T = 3 * (t-1)

L[S] = 0
Frontier = [S]
while Frontier:
    v = Frontier.pop(0)
    for i in G[v]:
        if L[i] < 0:
            Frontier.append(i)
            L[i] = L[v] + 1

print(L[T]//3)
### BUGGY CODE ###

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

ct = [0] * (n + 1)
e = [[] for _ in range(n + 1)]
c = {}

for _ in range(n - 1):
    a, b = map(int, input().split())
    e[a].append(b)

for _ in range(q):
    p, q = map(int, input().split())
    target = c.get(p)
    if target is None:
        tmp = [p]
        target = []
        while len(tmp):
            t = tmp.pop()
            target.append(t)
            for nt in e[t]:
                tmp.append(nt)
        c[p] = target
    for t in target:
        ct[t] += q

print(*ct[1:])

### FIXED CODE ###

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

ct = [0] * (n + 1)
e = [[] for _ in range(n + 1)]

for _ in range(n - 1):
    a, b = map(int, input().split())
    e[a].append(b)

qs = [0] * (n + 1)
for _ in range(q):
    p, q = map(int, input().split())
    qs[p] += q

target = [1]
while len(target):
    t = target.pop()
    ct[t] += qs[t]
    for nt in e[t]:
        target.append(nt)
        ct[nt] += ct[t]

print(*ct[1:])
### BUGGY CODE ###

def main():
  l=list(map(int,input().split()))
  x=[i for i in range(l[0],l[1]+1)]
  y=[j for j in range(l[2],l[3]+1)]
  all_pair=[i*j for i in x for j in y]
  print(sorted(all_pair)[-1])
if __name__=='__main__':
  main()

### FIXED CODE ###

import itertools
def main():
    l = list(map(int, input().split()))
    all_pair = []
    all_pair.append(l[0]*l[2])
    all_pair.append(l[0]*l[3])
    all_pair.append(l[1]*l[2])
    all_pair.append(l[1]*l[3])
    print(sorted(all_pair)[-1])
if __name__ == '__main__':
    main()
### BUGGY CODE ###

s=input()
n=int(input())
r=0
for i in range(n):
    strlist=input()
    if strlist[0]=='1':
        r+=1
    elif strlist[0]=='2' and strlist[2] == '1':
        if r%2==0:
            s = '{}{}'.format(strlist[4],s)
        else:
            s = '{}{}'.format(s,strlist[4])
    else:
        if r%2==0:
            s = '{}{}'.format(s,strlist[4])
        else:
            s = '{}{}'.format(strlist[4],s)
if r%2==0:
    print(s)
else:
    print(s[::-1])

### FIXED CODE ###

from collections import deque
s=deque(input())
n=int(input())
r=0
for i in range(n):
    strlist=input()
    if strlist[0]=='1':
        r+=1
    elif strlist[0]=='2' and strlist[2] == '1':
        if r%2==0:
            s.appendleft(strlist[4])
        else:
            s.append(strlist[4])
    elif strlist[0]=='2' and strlist[2] =='2':
        if r%2==0:
            s.append(strlist[4])
        else:
            s.appendleft(strlist[4])
if r%2==0:
    for s_ in s:
        print(s_, end='')
else:
    s.reverse()
    for s_ in s:
        print(s_, end='')