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

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

if p == 2 or p == 5:
  ans = 0
  for i,s in enumerate(S):
    if int(s)%p == 0:
      ans += i+1
  print(ans)
  exit()

M = [0]*p
pre = 0
ans = 0
i = 1
for s in S[::-1]:
  pre += int(s)*i
  pre %= p
  M[pre] += 1
  i *= 10

M[0] += 1
ans = sum(map(lambda m:(m*(m-1))//2, M))
print(ans)


### FIXED CODE ###

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

if p == 2 or p == 5:
  ans = 0
  for i,s in enumerate(S):
    if int(s)%p == 0:
      ans += i+1
  print(ans)
  exit()

def MS(i,s,pre):
  return (s*i +pre)%p
 
M = [0]*p
M[0] = 1
t = 1
now = 0
for i in S[::-1]:
    i = int(i)
    now += i*t
    now %= p
    M[now] += 1
    t = t*10%p

ans = sum(map(lambda m:(m*(m-1))//2, M))
print(ans)
### BUGGY CODE ###


def factorization(n):
    pf_cnt = {}
    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
            pf_cnt[i] = cnt

    if temp != 1: pf_cnt[temp] = 1
    if not pf_cnt: pf_cnt[n] = 1

    return pf_cnt

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

    al_fac = []
    for a in al:
        fac = factorization(a)
        al_fac.append(fac)

    gcd_l = [1]*n
    gcd_r = [1]*n

    gcd_l[0] = al_fac[0]
    gcd_r[-1] = al_fac[-1]

    for i in range(1,n):
        next_l = al_fac[i]
        next_l_gcd = {1:1}
        for prime,cnt in next_l.items():
            if prime in gcd_l[i-1]:
                next_l_gcd[prime] = min(cnt, gcd_l[i-1][prime])
        gcd_l[i] = next_l_gcd

        next_r = al_fac[n-i-1]
        next_r_gcd = {1:1}
        for prime,cnt in next_r.items():
            if prime in gcd_r[n-i]:
                next_r_gcd[prime] = min(cnt, gcd_r[n-i][prime])
        gcd_r[n-i-1] = next_r_gcd

    ans = 1
    for i in range(1,n-1):
        curr_gcd = 1
        for prime,cnt in gcd_l[i-1].items():
            if prime in gcd_r[i+1]:
                min_cnt = min(cnt, gcd_r[i+1][prime])
                curr_gcd *= prime**min_cnt
        ans = max(ans, curr_gcd)


    # i = 0
    curr_gcd = 1
    for prime,cnt in gcd_r[1].items():
        curr_gcd *= (prime**cnt)
    ans = max(ans, curr_gcd)

    # i = n-1
    curr_gcd = 1
    for prime,cnt in gcd_l[n-2].items():
        curr_gcd *= (prime**cnt)
    ans = max(ans, curr_gcd)

    # print(al_fac)
    # print(gcd_l)
    # print(gcd_r)
    print(ans)


if __name__ == "__main__":
    main()

### FIXED CODE ###

from fractions import gcd

def factorization(n):
    pf_cnt = {}
    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
            pf_cnt[i] = cnt

    if temp != 1: pf_cnt[temp] = 1
    if not pf_cnt: pf_cnt[n] = 1
    return pf_cnt


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

    gcd_l = [1]*n
    gcd_r = [1]*n

    gcd_l[0] = al[0]
    gcd_r[-1] = al[-1]

    for i in range(1,n):
        next_l = al[i]
        gcd_l[i] = gcd(next_l, gcd_l[i-1])

        next_r = al[n-i-1]
        gcd_r[n-i-1] = gcd(next_r, gcd_r[n-i])


    ans = max(gcd_r[1], gcd_l[n-2])
    for i in range(1,n-1):
        curr_gcd = gcd(gcd_l[i-1], gcd_r[i+1])
        ans = max(ans, curr_gcd)

    print(ans)


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

import bisect
N,Q = list(map(int,input().split(" ")))

hitos = []
ans = [-1] * Q
queries = []
events = []
for i in range(N):
    S,T,X =list(map(int,input().split(" ")))
    lt = S -X -0.5
    rt = T -X -0.5
    queries.append((lt,-1,X)) #-1 → 挿入クエリ lが時間、-1がクエリの種類、Xが場所
    queries.append((rt,1,X)) # 1 → 削除クエリ


queries.sort(key = lambda x:x[2])

for i in range(Q):
    t = int(input())
    queries.append((t,0,-99)) # 0 → チェッククエリ
queries.sort(key = lambda x:x[0])
for t,kind,x in queries:
    if kind == 0:
        if len(events) > 0:
            print(min(events))
        else:
            print(-1)
    if kind == -1:
        events.append(x)
    if kind == 1:
        events.remove(x)



### FIXED CODE ###

import bisect
import heapq
import sys
N,Q = [int(x) for x in sys.stdin.readline().split()]

hitos = []
ans = [-1] * Q
queries =[]
jump = [-1] * Q



queries = [[int(x) for x in sys.stdin.readline().split()] for i in range(N)]
hitos = [int(sys.stdin.readline()) for i in range(Q)]


# for i in range(N):
    # S,T,X =list(map(int,input().split(" ")))
    # lt = S -X -0.5
    # rt = T -X -0.5
    # queries.append([lt,rt,X]) #-1 → 挿入クエリ lが時間、-1がクエリの種類、Xが場所


queries.sort(key=lambda x:x[2])





for l,r,x in queries:
     lind  = bisect.bisect_left(hitos,l-x - 0.5)
     rind  = bisect.bisect_left(hitos,r -x - 0.5)
     while lind < rind:
         if ans[lind] == -1:
            ans[lind] = x
            jump[lind] = rind
            lind += 1
         else:
             temp = jump[lind]
             jump[lind] = rind
             lind = temp

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

s = list(input())
s = s[::-1]
N = len(s)
mod = pow(10,9)+7
dp = [[0]*13 for i in range(N)]
if s[0] == '?':
    for i in range(10):
        dp[0][i] = 1
else:
    a = int(s[0])
    dp[0][a] = 1
for i in range(1,N):
    if s[i] == '?':
        for j in range(10):
            k = (j*10**i) % 13
            for m in range (13):
                 dp[i][(m+k)%13] += dp[i-1][m]
    else:
        k = (int(s[i])*(10**i)) % 13
        for m in range(13):
            dp[i][(m+k)%13] += dp[i-1][m]
print(dp[-1][5]% mod)

### FIXED CODE ###

s =list(input())
N = len(s)
mod = pow(10,9)+7
dp = [[0]*13 for i in range(N)]
if s[0] == '?':
        dp[0][0:9] = [1 for i in range(10)]
else:
    dp[0][int(s[0])] = 1
for i in range(1,N):
    if s[i] == '?':
        for j in range(10):
            for m in range (13):
                 dp[i][(m*10+j)%13] += dp[i-1][m]%mod
    else:
        for m in range(13):
            dp[i][(m*10+int(s[i]))%13] += dp[i-1][m]%mod
print(dp[-1][5]% mod)
### BUGGY CODE ###

import itertools
from sys import stdin
N=int(input())
st=list(stdin.readline().strip())
count=0
cnt=0
num=["0","1","2","3","4","5","6","7","8","9"]

num_list= ["".join(i) for i in itertools.product(num,repeat=3)]
for number in num_list:
    mark = 0
    for i in range(N):
        if cnt==0 and number[0]==st[i]:
            mark=i
            cnt+=1
        if cnt==1 and number[1]==st[i] and i>mark:
            cnt+=1
            mark=i
        if cnt==2 and number[2]==st[i] and i>mark:
            cnt+=1
            break
    if cnt==3:
        count+=1
    cnt=0
print(count)

### FIXED CODE ###

def main():
  N = int(input())
  S = list(map(int,input()))
  ans = 0
  for i in range(10):
    for j in range(10):
      for k in range(10):
        flg = False
        flg2 = False
        for x in range(N):
          if flg2:
            break
          if not flg:
            if S[x] == i:
              flg = True
          else:
            if S[x] == j:
              flg2 = True
              if k in S[x+1:]:
                ans +=1
  print(ans)
main()
### BUGGY CODE ###

# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left,bisect_right
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    a=list(map(int,input().split()))
    edge=[[] for _ in range(N)]
    for _ in range(N-1):
        x,y=map(int1,input().split())
        edge[x].append(y)
        edge[y].append(x)
    stack=[(0,1)]
    used=[False]*N
    ans=[0]*N
    dpdp=[[0]+[INF]*(N+10)]
    prev_l=1
    while stack:
        v,l=stack.pop()
        used[v]=True
        for _ in range(prev_l-l):
            dpdp.pop()
        prev_l=l
        dp=dpdp[-1][:]
        dp[bisect_right(dp,a[v]-1,hi=l)]=a[v]
        ans[v]=bisect_left(dp,INF,hi=l+1)-1
        f=True
        for nv in edge[v]:
            if not used[nv]:
                if f:
                    dpdp.append(dp)
                    f=False
                stack.append((nv,l+1))
    for a in ans:
        print(a)

if __name__ == '__main__':
    main()


### FIXED CODE ###

# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left,bisect_right
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    a=list(map(int,input().split()))
    edge=[[] for _ in range(N)]
    for _ in range(N-1):
        x,y=map(int1,input().split())
        edge[x].append(y)
        edge[y].append(x)
    stack=[(0,1)]
    used=[False]*N
    ans=[0]*N
    dp=[INF]*(N+1)
    dp[0]=0
    dpdp=[]
    prev_l=1
    def dfs(v,l):
        used[v]=True
        index=bisect_right(dp,a[v]-1,hi=l)
        dpdp=(index,dp[index])
        dp[index]=a[v]
        ans[v]=bisect_left(dp,INF,hi=l+1)-1
        for nv in edge[v]:
            if not used[nv]:
                i,x=dfs(nv,l+1)
                dp[i]=x
        return dpdp
    dfs(0,1)
    for a in ans:
        print(a)

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

import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for _ in range(j)] for _ in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from itertools import accumulate #list(accumulate(A))
import copy
N, M = mi()
D = dp2(float('inf'), N, N)
memo = []
cnt = 0

for i in range(M):
    s, t = mi()
    s, t = s-1, t-1
    memo.append((s, t))
    D[s][t] = D[t][s] = 1

for x in range(M):
    d = copy.deepcopy(D)
    s, t = memo[x][0], memo[x][1]
    d[s][t] = d[t][s] = float('inf')
    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])

    for i in range(N):
        for j in range(i+1, N):
            if d[i][j] == float('inf'):
                cnt += 1
                break
        else:
            continue
        break

print(cnt)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for _ in range(j)] for _ in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from itertools import accumulate #list(accumulate(A))

class UnionFind:
    def __init__(self, n):
        self.d = [-1]*n
    
    def find(self, x):
        if self.d[x] < 0:
            return x
        else:
            self.d[x] = self.find(self.d[x])
            return self.find(self.d[x])
    
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x==y:
            return False
        if self.d[x] > self.d[y]:
            x, y = y, x
        self.d[x] += self.d[y]
        self.d[y] = x
        return True
    
    def same(self, x, y):
        if self.find(x)==self.find(y):
            return True
        return False
    
    def size(self, x):
        return (-1) * self.d[self.find(x)]

N, M = mi()
ab = li2(M)
cnt = M

for i in range(M):
    T = UnionFind(N)
    for j in range(M):
        if i != j:
            a, b = ab[j][0]-1, ab[j][1]-1
            if not T.same(a, b):
                T.unite(a, b)
    for k in range(N):
        if T.size(k) != N:
            break
    else:
        cnt -= 1

print(cnt)
### BUGGY CODE ###

#C
L, R = list(map(int, input().split()))
result = 2018
for i in range(L,R+1):
    for s in range(i+1,R+1):
        x = (i*s)%2019
        if result >= x:
            result = x
            if result == 0:
                break
print(result)

### FIXED CODE ###

#C
import sys
L, R = list(map(int, input().split()))
if (R - L) == 2019:
    result = 0
else:
    result = 2018
    for i in range(L,R+1):
        for s in range(i+1,R+1):
            x = (i*s)%2019
            if x == 0:
                result = 0
                print(0)
                sys.exit()
            elif result > x:
                result = x
print(result)
### BUGGY CODE ###

from math import factorial

n, m = map(int, input().split())
if abs(n - m) > 1:
    print(0)
elif n == m:
    print((factorial(n) * factorial(m) * 2) % (10 ** 9 + 7))
else:
    print(factorial(n) * factorial(m))

### FIXED CODE ###

def factorial(x):
    res = 1
    for i in range(1, x):
        res *= i + 1
        res %= 10 ** 9 + 7
    return res

n, m = map(int, input().split())
if abs(n - m) > 1:
    print(0)
elif n == m:
    print((factorial(n) * factorial(m) * 2) % (10 ** 9 + 7))
else:
    print(factorial(n) * factorial(m) % (10 ** 9 + 7))
### BUGGY CODE ###

S=input()
mem_mod = [0 for i in range(0,2019,1)]
N = len(S)
counter = 0
S_num_tmp = list(S)
S_num = list(map(int, S_num_tmp))
tmp=10

for i in range(1,N,1):
    S_num[N-i-1] = (S_num[N-i] + ((tmp)*S_num[N-i-1]))%2019
    tmp=tmp*10

for i in range(0,N,1):
    X = S_num[N-i-1]
    if X==0:
        counter+=1
    counter += mem_mod[X]
    mem_mod[X] += 1
print(counter)


### FIXED CODE ###

import collections
p = 2019
s=input()
n=len(s)
arr=[int(s[i]) for i in range(len(s))] #文字列の各文字をそれぞれ数字に変換しておく
if p==2 or p==5: #P=2,5のときは10を割り切るので連続部分列の右端のみを見ればよい
 ans=0
 for i in range(n):
   if arr[i]%p==0:
     ans+=i+1
 print(ans)
else: #Pが2でも5でもないとき
 dic=collections.defaultdict(int)
 tmp=0
 for i in range(n-1,-1,-1): #右端の要素を右端とする連続部分列のあまりを順に求める
   tmp+=arr[i]*pow(10,n-1-i,p)
   tmp%=p
   dic[tmp]+=1
 ans=0
 rem=0 #調べるあまりの値(初期値は0)
 for i in range(n-1,-1,-1):
   ans+=dic[rem]
   rem+=arr[i]*pow(10,n-1-i,p) #調べるあまりの値に(i番目の要素)*10^(n-1-i)を加える
   rem%=p
   dic[rem]-=1 #右端の要素が右端、i番目の要素が左端となる連続部分列のあまりの個数を1減らす
 print(ans)
### BUGGY CODE ###

N = int(input())
A = list(map(int,input().split()))
ans = 0
count_list = []
A_sl = list(set(A))
if len(A_sl) == 1:
    print(len(A))
elif len(A_sl) == 2:
    if A_sl[1] - A_sl[0] <= 2:
        print(len(A))
    else:
        count_l = A.count(A_sl[1])
        count_s = A.count(A_sl[0])
        print(max(count_l,count_s)) 
else:
    for i in range(min(A),max(A) + 1):
        count_i = A.count(i)
        count_list.append(count_i)
    for i in range(1,max(A)-min(A)):
        count = count_list[i-1] + count_list[i] + count_list[i+1]
        if count > ans:
            ans = count
    print(ans)

### FIXED CODE ###

N = int(input())
A = list(map(int,input().split()))
l = [0]*(10**5)
for e in A:
    if e == 0:
        l[0] += 1
        l[1] += 1
    elif e == 99999:
        l[99999] += 1
        l[99998] += 1
    else:
        l[e-1] += 1
        l[e] += 1
        l[e+1] += 1
print(max(l))
### BUGGY CODE ###

N="0"+input()
N=N[::-1]
DP=[[0,0]for i in range(len(N))]

DP[0][0]=int(N[0])
DP[0][1]=10-int(N[0])

#print(DP)
#print(N)
for i in range(1,len(N)):
    DP[i][0]=min(DP[i-1][0]+int(N[i]),DP[i-1][1]+int(N[i])+1)
    DP[i][1]=min(DP[i-1][0]+10-int(N[i]),DP[i-1][1]+10-(int(N[i])+1))
#print(DP)
print(min(DP[-1]))

### FIXED CODE ###

N="0"+input()
N=N[::-1]
DP=[[0,0]for i in range(len(N))]

DP[0][0]=int(N[0])
DP[0][1]=10-int(N[0])

#print(DP)
#print(N)
for i in range(1,len(N)):
    DP[i][0]=min(DP[i-1][0]+int(N[i]),DP[i-1][1]+int(N[i])+1)
    DP[i][1]=min(DP[i-1][0]+10-int(N[i]),DP[i-1][1]+10-(int(N[i])+1))
#print(DP)
print(min(DP[-1]))
### BUGGY CODE ###

#!/usr/bin/env python3

"""
https://atcoder.jp/contests/agc029/tasks/agc029_a
"""

import sys


s = sys.stdin.readline().rstrip()
s2 = ''
cnt = 0

while True:
    s2 = s.replace('BW', 'WB', 1)
    if s2 == s:
        break
    cnt += 1
    s = s2


print(cnt)

### FIXED CODE ###

#!/usr/bin/env python3

"""
https://atcoder.jp/contests/agc029/tasks/agc029_a
"""

import sys
import re


s = sys.stdin.readline().rstrip()
e = 0
n = 0

for chr in s:
    if chr == 'W':
        e += n

    if chr == 'B':
        n += 1

print(e)
### BUGGY CODE ###

I = [int(_) for _ in open(0).read().split()]
N, Q = I[:2]
C = [0] + I[2:2 + N]
LR = I[2 + N:]


class BinaryIndexedTree():
    def __init__(self, n):
        """
        constructs binary indexed tree

        Parameters
        ----------
        n : int
            maximum index value
        """
        self.n = n
        self.dat = [0] * (n + 1)

    def sum(self, i):
        """
        returns the sum of [1, i]

        Parameters
        ----------
        i : int
            right end of the interval
        """
        s = 0
        while i:
            s += self.dat[i]
            i -= i & -i
        return s

    def add(self, i, x):
        """
        adds x to i-th element

        Parameters
        ----------
        i : int
            index
        x : int
            additional value
        """
        while i <= self.n:
            self.dat[i] += x
            i += i & -i


BIT = BinaryIndexedTree(500010)

arr = [5 * 10**5 + 4] * (5 * 10**5 + 5)
RLI = sorted((lr[1], lr[0], i) for i, lr in enumerate(zip(LR[::2], LR[1::2])))
ans = [None] * Q
j = 0
for r, l, i in RLI:
    for j in range(j, r):
        j += 1
        if arr[C[j]]:
            BIT.add(arr[C[j]], -1)
        arr[C[j]] = j
        BIT.add(j, 1)
    ans[i] = BIT.sum(r) - BIT.sum(l - 1)
print('\n'.join(map(str, ans)))


### FIXED CODE ###

I = [int(_) for _ in open(0).read().split()]
N, Q = I[:2]
C = [0] + I[2:2 + N]
LR = I[2 + N:]
L, R = LR[::2], LR[1::2]


class BinaryIndexedTree():
    def __init__(self, n):
        """
        constructs binary indexed tree

        Parameters
        ----------
        n : int
            maximum index value
        """
        self.n = n
        self.dat = [0] * (n + 1)

    def sum(self, i):
        """
        returns the sum of [1, i]

        Parameters
        ----------
        i : int
            right end of the interval
        """
        s = 0
        while i:
            s += self.dat[i]
            i -= i & -i
        return s

    def add(self, i, x):
        """
        adds x to i-th element

        Parameters
        ----------
        i : int
            index
        x : int
            additional value
        """
        while i <= self.n:
            self.dat[i] += x
            i += i & -i


BIT = BinaryIndexedTree(500010)

arr = [5 * 10**5 + 4] * (5 * 10**5 + 5)
RLI = sorted(r * (2 ** 40) + l * (2 ** 20) + i for r, l, i in zip(R, L, range(Q)))
ans = [None] * Q
j = 0
for rli in RLI:
    r, li = divmod(rli, 2 ** 40)
    l, i = divmod(li, 2 ** 20)
    for j in range(j + 1, r + 1):
        BIT.add(arr[C[j]], -1)
        arr[C[j]] = j
        BIT.add(j, 1)
    ans[i] = BIT.sum(r) - BIT.sum(l - 1)
print('\n'.join(map(str, ans)))
### BUGGY CODE ###

def bitcount(N):  # 立ってるbitの数
    bitcnt = [0]
    for _ in range(N):
        bitcnt += [i + 1 for i in bitcnt]
    return bitcnt


n, x = int(input()), input()

num, cnt = int(x, 2), x.count('1')
lbit = bitcount(18)
for i in range(n):
    ans = 1
    if x[i] == '0':
        ctmp = cnt + 1
        tmp = num + pow(2, n - (i + 1), ctmp)
    elif x[i] == '1':
        if cnt == 1:
            print(0)
            continue
        ctmp = cnt - 1
        tmp = num - pow(2, n - (i + 1), ctmp)
    tmp %= ctmp
    ctmp = lbit[tmp]
    while tmp > 0:
        ans += 1
        tmp %= ctmp
        ctmp = lbit[tmp]
    print(ans)


### FIXED CODE ###

def bitcount(N):  # 立ってるbitの数
    bitcnt = [0]
    for _ in range(N):
        bitcnt += [i + 1 for i in bitcnt]
    return bitcnt


n, x = int(input()), input()

num, cnt = int(x, 2), x.count('1')
lbit = bitcount(18)
for i in range(n):
    ans = 1
    if x[i] == '0':
        ctmp = cnt + 1
        tmp = num % ctmp + pow(2, n - (i + 1), ctmp)
    elif x[i] == '1':
        ctmp = cnt - 1
        if ctmp == 0:
            print(0)
            continue
        tmp = num % ctmp - pow(2, n - (i + 1), ctmp)
    tmp %= ctmp
    ctmp = lbit[tmp]
    while tmp > 0:
        ans += 1
        tmp %= ctmp
        ctmp = lbit[tmp]
    print(ans)
### BUGGY CODE ###

def main():
  import bisect
  import sys
  from itertools import accumulate
  input = sys.stdin.readline
  def hsnum(ls,x):
    num = 0
    for i in range(n):
      y = x-ls[i]
      num += n-bisect.bisect_left(ls,y)
    return num
  n,m = map(int, input().split())
  a = list(map(int, input().split()))
  a.sort()
  suma = [0]+list(accumulate(a))
  lx = 0
  rx = 2*10**5+2
  error = 0
  while lx < rx:
    mx = (lx+rx)//2
    if hsnum(a,mx) < m:
      rx = mx
    elif hsnum(a,mx) > m:
      if hsnum(a,mx+1) < m:
        error = hsnum(a,mx)-m
        lx = mx
        break
      lx = mx + 1
    else:
      lx = mx
      break
  ans = 0
  for i in a:
    rema = lx - i
    j = bisect.bisect_left(a,rema)
    ans += (n-j)*i+suma[n]-suma[j]
  print(ans-error*lx)
if __name__ == "__main__":
    main()

### FIXED CODE ###

def main():
  import bisect
  import sys
  from itertools import accumulate
  input = sys.stdin.readline
  def hsnum(x):
    num = 0
    for i in a:
      y = x-i
      num += n-bisect.bisect_left(a,y)
    return num
  n,m = map(int, input().split())
  a = list(map(int, input().split()))
  a.sort()
  suma = [0]+list(accumulate(a))
  lx = 0
  rx = 2*10**5+2
  error = 0
  while lx+1 < rx:
    mx = (lx+rx)//2
    if hsnum(mx) < m:
      rx = mx
    elif hsnum(mx) > m:
      lx = mx + 1
    else:
      lx = mx
      break
  if hsnum(lx)<m:
    lx -= 1
  error = hsnum(lx)-m
  ans = 0
  for i in a:
    rema = lx - i
    j = bisect.bisect_left(a,rema)
    ans += (n-j)*i-suma[j]
  ans += suma[n]*n
  print(ans-error*lx)
if __name__ == "__main__":
    main()
### BUGGY CODE ###


INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def query1(s):
    s=s[::-1]
    #print(s)
    return s
def query2(s,f,c):
    if f=='1':
        s=c+s
    else:
        s=s+c
    
    #print(s)
    return s
    
def do():
    S=STR()
    q=INT()
    for i in range(q):
        qt=LISTS()
        if qt[0]=='1':
            S=query1(S)
        else:
            S=query2(S,qt[1],qt[2])
            
    print(S)
    
if __name__ == '__main__':
    do()

### FIXED CODE ###

INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))
def do():
    s=STR()
    q=INT()
    l=''
    r=''
    ct=0
    for i in range(q):
        fc=LISTS()
        if fc[0]=="1":
            ct+=1
        else:
            if fc[1]=="1":
                if ct%2==0:
                    l=fc[2]+l
                else:
                    r=r+fc[2]
            else:
                if ct%2==1:
                    l=fc[2]+l
                else:
                    r=r+fc[2]
    
    sums=l+s+r
    if ct%2==1:
        ans=""
        for i in range(len(sums)-1,-1,-1):
            ans=ans+sums[i]
    else:
        ans=sums
    
    print(ans)
                
if __name__ == '__main__':
    do()
### BUGGY CODE ###

s=list(input())
top=bool()
n=int(input())
for i in range(n):
  q=list(map(str,input().split()))
  if q[0]=='1':
    top=not top
  else:
    if (q[1]=="1") ^ top:
      s.insert(0,q[2])
    else:
      s.append(q[2])
if top:
  print(*list(reversed(s)),sep='')
else:
  print(*s,sep='')


### FIXED CODE ###

s=list(input())
top=bool()
t=[]
u=[]
n=int(input())
for i in range(n):
  q=list(map(str,input().split()))
  if q[0]=='1':
    top=not top
  else:
    if (q[1]=="1") ^ top:
      t.append(q[2])
    else:
      u.append(q[2])
s=list(reversed(t))+s+u
if top:
  print(*list(reversed(s)),sep='')
else:
  print(*s,sep='')