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

import sys
from heapq import heappop, heappush
input = sys.stdin.readline

def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return sorted([list(map(int, input().split())) for _ in range(n)])
def graphm():
    n=inp()
    g=[[] for _ in range(n)]
    for _ in range(n-1):
        a,b,w=inpm()
        a-=1
        b-=1
        g[a].append((b,w))
        g[b].append((a,w))
    return n,g
def dijkstra(s,to,n,g): # sからの最短距離 頂点数n
    s -= 1
    que = []
    d = [10**15 for _ in range(n)]
    d[s] = 0
    heappush( que,(0,s) )
    while len(que)>0:
        p =  heappop(que)
        v = p[1]
        if d[v] < p[0]:
            if p[1]==to-1:
                break
            continue
        for i in range(len(g[v])):
            edge = g[v][i]
            if d[edge[0]] > d[v] + edge[1]:
                d[edge[0]] = d[v] + edge[1]
                heappush( que,(d[edge[0]] , edge[0]) )
    return d[to-1]

def dijkstra1(s,n,g): # sからの最短距離 頂点数n
    s -= 1
    que = []
    d = [10**15 for _ in range(n)]
    d[s] = 0
    heappush( que,(0,s) )
    while len(que)>0:
        p =  heappop(que)
        v = p[1]
        if d[v] < p[0]:
            continue
        for i in range(len(g[v])):
            edge = g[v][i]
            if d[edge[0]] > d[v] + edge[1]:
                d[edge[0]] = d[v] + edge[1]
                heappush( que,(d[edge[0]] , edge[0]) )
    return d

def main():
    n,graph = graphm()
    q,k = inpm()
    pre = dijkstra1(k,n,graph)
    for _ in range(q):
        x,y = inpm()
        print( dijkstra(x,k,n,graph) + pre[y-1] )    

if __name__ == "__main__":
    main()


### FIXED CODE ###

from collections import Counter,defaultdict,deque
import sys
import copy
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n=int(input())
    graph = [[] for _ in range(n)]
    for _ in range(n-1):
        a,b,w=map(int,input().split())
        a-=1
        b-=1
        graph[a].append((b,w))
        graph[b].append((a,w))
    graph = tuple(graph)
    q,k = map(int,input().split())
    que = deque([k-1])
    dis = [-1 for _ in range(n)]
    dis[k-1]=0
    while que:
        i = que.pop()
        for j in range(len(graph[i])):
            go = graph[i][j][0]
            d = graph[i][j][1]
            if dis[go]==-1:
                dis[go] = dis[i] + d
                que.append(go)
    for _ in range(q):
        x,y = map(int,input().split())
        print( dis[x-1] + dis[y-1] ) 

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
#input = sys.stdin.readline


def resolve():
    n, m = map(int, input().split())

    p_list, s_list = [], []
    for i in range(m):
        p, s = input().split()
        p_list.append(int(p))
        s_list.append(s)

    sum_wa = 0
    ac_num = 0
    ac_list = []
    wa_dic = {}
    for i in range(m):
        if p_list[i] in ac_list:
            continue

        if s_list[i] == "AC":
            ac_num += 1
            ac_list.append(p_list[i])
            if p_list[i] in wa_dic.keys():
                sum_wa += wa_dic[p_list[i]]
        else:
            if p_list[i] in wa_dic.keys():
                wa_dic[p_list[i]] += 1
            else:
                wa_dic[p_list[i]] = 1

    print(ac_num, sum_wa)

if __name__ == "__main__":
    resolve()



### FIXED CODE ###

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
#input = sys.stdin.readline


def resolve():
    n, m = map(int, input().split())
    all_wa = 0
    all_ac = 0
    ac_list = []
    p_list, s_list = [], []
    first_ac_dic = {}

    wa_count_dic = {}
    wa_num = 0
    for i in range(m):
        p, s = input().split()
        p = int(p)
        p_list.append(p)
        s_list.append(s)

        if s == "AC":
            if p in first_ac_dic:
                pass
            else:
                first_ac_dic[p] = i
                wa_num += wa_count_dic.get(p, 0)
        else:
            wa_count_dic[p] = wa_count_dic.get(p, 0) + 1

    ans_ac = len(first_ac_dic)

    print(ans_ac, wa_num)


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

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

num_cnt = [0]*n
res = 0
for num in range(n):
    cnt = a.count(num+1)
    num_cnt[num] = cnt
    if cnt > 0:
        res += cnt*(cnt-1)//2

for a_k in a:
    cnt = num_cnt[a_k-1]
    print(res - (cnt-1)*(cnt - (cnt-2))//2)

### FIXED CODE ###

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

import collections
cnt = collections.Counter(a)

sum_cnt = 0
for v in cnt.values():
    sum_cnt += v*(v-1)//2

res = []
for value in a:
    res.append(str( sum_cnt - (cnt[value]-1) ))
print('\n'.join(res))
### BUGGY CODE ###

N = int(input())
n = [int(input()) for i in range(N)]

def Is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i < int(n ** (0.5))+ 1:
        if n % i == 0:
            return False
    return True

count = 0
for j in n:
    if Is_prime(j):
        count += 1

print (count)

### FIXED CODE ###

N = int(input())
n = [int(input()) for i in range(N)]

def Is_prime(n):
    if n == 2:
        return True
    if n == 1:
        return False
    if n % 2 == 0:
        return False
    i = 3
    while i < int(n ** (0.5))+ 1:
        if n % i == 0:
            return False
        i += 2
    return True

count = 0
for j in n:
    if Is_prime(j):
        count += 1

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

from collections import defaultdict
MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = 10 ** 13

def bfs(graph, N, M):
    que = []

    visited = [-INF for x in range(MAX_N)]
    update_cnt = [0 for x in range(MAX_N)]

    que.append(0)
    visited[0] = 0
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now
        cost = visited[pos]

        if (visited[pos] > cost):
            continue
        if (update_cnt[pos] >= MAX_M):
            continue
        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]
            if (cost + nxt_cost > visited[nxt]):
                visited[nxt] = cost + nxt_cost
                update_cnt[nxt] += 1
                que.append(nxt)

    if (update_cnt[N - 1] >= MAX_N):
        return (0, False)
    return (visited[N - 1], True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = defaultdict(list)
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        print ('inf')
    else:
        print (res)


### FIXED CODE ###


MAX_N = 10 ** 3 + 10
MAX_M = 2 * (10 ** 3) + 1
INF = 10 ** 13

def bfs(graph, N, M):
    que = []
    que.append([0, 0])
    visited = [-INF for x in range(MAX_N)]
    update_cnt = [0 for x in range(MAX_N)]
    result = -INF
    while (len(que) > 0):
        now = que[0]
        que.pop(0)

        pos = now[0]
        cost = now[1]
        if (visited[pos] > cost):
            continue
        for val in graph[pos]:
            nxt = val[0]
            nxt_cost = val[1]

            if (cost + nxt_cost > visited[nxt] and update_cnt[nxt] < MAX_M):
                visited[nxt] = cost + nxt_cost
                update_cnt[nxt] += 1
                que.append([nxt, nxt_cost + cost])

    if (update_cnt[N - 1] >= MAX_N):
        return (0, False)
    return (visited[N - 1], True)


if __name__ == "__main__":
    N, M = map(int, input().split())
    graph = [[] for x in range(MAX_N)]
    for x in range(M):
        a,b,c = map(int, input().split())
        a -= 1
        b -= 1
        graph[a].append([b, c])
    res,ok = bfs(graph, N, M)
    if (not ok):
        print ('inf')
    else:
        print (res)
### BUGGY CODE ###

import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
import numpy as np
import bisect

def main():
	h,w=map(int,input().split())
	AB=np.array(read().split(), np.int64)
	
	
	A=AB[:h*w]
	B=AB[h*w:]
	
	A=np.reshape(A, (h,w))
	B = np.reshape(B, (h, w))
	
	G=abs(A-B)
	
	li=[[[]for i in range(w)] for j in range(h)]
	for i in range(h):
		for j in range(w):
			if i==j==0:
				li[i][j].append(G[i][j])
			elif i==0:
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			elif j==0:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			else:
				for k in li[i-1][j]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
				for k in li[i][j-1]:
					li[i][j].append(abs(k-G[i][j]))
					li[i][j].append(abs(k + G[i][j]))
			s=set(li[i][j])
			li[i][j]=sorted(list(s))
			idx=bisect.bisect_left(li[i][j],h*w*80)
			li[i][j]=li[i][j][:idx]
			
	print(min(li[h-1][w-1]))
	
if __name__ == "__main__":
	main()


### FIXED CODE ###

import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines


# mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
# import numpy as np

def main():
	h, w = map(int, input().split())
	
	G = [[0] * w for i in range(h)]
	A = [0]*h
	B = [0]*h
	
	for i in range(h):
		A[i] = list(map(int, input().split()))
	for i in range(h):
		B[i] = list(map(int, input().split()))
	
	for i in range(h):
		for j in range(w):
			G[i][j]=abs(A[i][j]-B[i][j])

	M = (h + w) * 80

	li = [[[0] * M for i in range(w)] for j in range(h)]
	
	li[0][0][G[0][0]] = 1
	for i in range(h):
		for j in range(w):
			for k in range(M):
				
				if li[i][j][k] == 1:
					if i < h - 1:
						li[i + 1][j][abs(k - G[i+1][j])] = 1
						li[i + 1][j][abs(k + G[i+1][j])] = 1
					if j < w - 1:
						li[i][j + 1][abs(k - G[i][j+1])] = 1
						li[i][j + 1][abs(k + G[i][j+1])] = 1

	for i in range(M):
		if li[h-1][w - 1][i] == 1:
			print(i)
			exit(0)


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

import sys
input =sys.stdin.readline

N=int(input().rstrip('\n'))
s = []
for _ in range(N):
  A,B = (int(x) for x in input().rstrip('\n').split())
  s.append([A,B])
used = 0
now = 0
check = 0
for i in range(N):
  x = min([i[1] for i in s])
  y = min([i[0] for i in s if i[1]==x])
  used += y
  d = s.index([a for a in s if a==[y,x]][0])
  s.pop(d)
  if used > x:
    check += 1
    print('No')
    break
if check == 0:
  print('Yes')


### FIXED CODE ###

import sys
input =sys.stdin.readline

N=int(input().rstrip('\n'))
s = {}
for _ in range(N):
  A,B = (int(x) for x in input().rstrip('\n').split())
  if B in s:
    s[B] += A
  else:
    s[B] = A
m = sorted(list(set(s)))
check = 0
used = 0
for i in m:
  used += s[i]
  if used > i:
    check += 1
    print('No')
    break
if check == 0:
  print('Yes')
### BUGGY CODE ###

import sys

sys.setrecursionlimit(10 ** 6)

mod = 10 ** 9 + 7

input = sys.stdin.readline


def rec(v, bf):
    global ans
    gs[v] += 1
    gs[bf] += 1
    ans = ans * (K - gs[bf]) % mod
    for nv in es[v]:
        if nv == bf: continue
        rec(nv, v)
    return


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

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

gs = [0] * (N + 1)
gs[0] = -1
gs[N] = -1

ans = 1

rec(0, N)
print(ans)


### FIXED CODE ###

import sys

sys.setrecursionlimit(10 ** 6)

mod = 10 ** 9 + 7

input = sys.stdin.readline


def rec(v, bf):
    global ans
    gs[v] += 1
    gs[bf] += 1
    ans = ans * (K - gs[bf]) % mod
    for nv in es[v]:
        if nv == bf: continue
        rec(nv, v)
    return


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

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

gs = [0] * (N + 1)
gs[0] = -1
gs[N] = -1

ans = 1

rec(0, N)
print(ans)
### BUGGY CODE ###

def combi(n):
  return n*(n-1)//2
 
import sys
input = sys.stdin.readline
N = int(input())
A = input().split()
tmp = 0
idx = list(set(A))
value = [ A.count(_) for _ in idx ]
for n in value:
    tmp += combi(n)
#sum = 0
for i in A:
    j = idx.index(i)
    #sum += tmp - combi(j) + combi(j-1)
    print(int(tmp - combi(value[j]) + combi(value[j]-1)))

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
 
import collections
A_count = collections.Counter(A)
 
import math
sum_ = 0
for ai in A_count:
    sum_ += (A_count[ai] * (A_count[ai] - 1)) // 2
 
for ai in A:
    #print(sum_ - (A_count[ai] * (A_count[ai] - 1)) // 2 + (A_count[ai] - 1) * (A_count[ai] - 2)) // 2
    l = A_count[ai] * (A_count[ai] - 1) // 2
    m = (A_count[ai] - 1) * (A_count[ai] - 2) // 2
    print(sum_ - l + m)
### BUGGY CODE ###

import numpy as np
N,K=map(int, input().split())

A=list(map(int, input().split()))
K=min(K, 30)
for k in range(K):
    B=[0]*(N+1)
    for i in range(N):
        a=A[i]
        start=max(0,i-a)
        end=min(N,i+a+1)
        B[start]+=1
        B[end]-=1
    B=np.array(B)
    B=np.cumsum(B)[:N]
    if B.min()==N:
        break
    #print(B)
    A=B.copy()
    
print(*B)

### FIXED CODE ###

#import numpy as np
N,K=map(int, input().split())

A=list(map(int, input().split()))
#K=min(K, 30)
for k in range(K):
    B=[0]*(N+1)
    for i in range(N):
        a=A[i]
        start=max(0,i-a)
        end=min(N,i+a+1)
        B[start]+=1
        B[end]-=1
    #B=np.array(B)
    A=[0]*N
    A[0]=B[0]
    for i in range(1,N):
        A[i]=A[i-1]+B[i]

    if min(A)==N:
        break
    #print(B)
    
    
print(*A)
### BUGGY CODE ###

import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal  #変換後の末尾桁を0や0.01で指定
  #Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
from bisect import bisect_left as bileft, bisect_right as biright
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########

n=int(input())

A=list(map(int,input().split()))
from math import sqrt
def eratosu(n):
  if not isinstance(n,int):
    raise TypeError("nがint型になってねえぞ")
  if n<2:
    raise ValueError('nが2よりちっちぇえぞ')
  prime = []
  limit = sqrt(n)
  data = [i+1 for i in range(1, n)]  #2,3,4,...,n
  while True:
    p = data[0]
    if limit <= p:
        return prime + data
    prime.append(p)
    data = [e  for e in data if e % p != 0]
PRIME=eratosu(10**6+10)
@lru_cache(maxsize=10**10)
def bunkai(n):
    if n==1:return []
    ans=[]
    temp=n
    #そんな早くしなくてよかったり、何回もするわけじゃないなら、
    #for i in range(2,int(sqrt(n))+1): とかで
    primelist= PRIME
    for i in primelist:
        if i>sqrt(n):break
        if temp % i ==0:
            ji=0
            while temp%i==0:
                ji+=1
                temp//=i
            ans.append(i)
    if ans==[]:return([n])  #素数のとき
    if temp!=1:
        ans.append(temp)  #4*5882353とか
    return ans

flag=1
seen={i:0 for i in PRIME}
#print(bunkai(3))
for i in A:
    for l in bunkai(i):
        now=l
        if now==1:continue
        if seen[now]!=0:
            flag=0
        seen[now]+=1
if flag:
    print("pairwise coprime")
elif max(seen.values())!=n:
    print("setwise coprime")
else:
    print("not coprime")

#print(seen)


### FIXED CODE ###

n=int(input())
A=list(map(int,input().split()))
def Dlist(BIG):
    D=[1]*(BIG+1)
    for p in range(2,BIG+1):
        if D[p]!=1:
            continue
        for i in range(p,BIG+1,p):
            if D[i]==1:
                D[i]=p
    return D

D=Dlist(max(A))
def SOINSU(num,D): #素因数だけ列挙(setしただけ)
    now=num ; ans=set()
    while now>1:
        ans.add(D[now])
        now//=D[now]
    return ans

seen=[0]*(10**6+10)
flag=1
for num in A:
    for i in SOINSU(num,D):
        if seen[i]!=0: flag=0
        seen[i]+=1
if flag:
    print("pairwise coprime")
elif max(seen)!=n:
    print("setwise coprime")
else:
    print("not coprime")
### BUGGY CODE ###

# 自分の
N = int(input())
a_arr = list(map(int, input().split()))

for i in range(N):
    if i==N-1:
        print("YES")
        break
    for j in range(1, N-i):
        if a_arr[i] == a_arr[i+j]:
            print("NO")
            break
    else:
        continue
    break

### FIXED CODE ###

# 自分の
N = int(input())
a_arr = list(map(int, input().split()))

new_a_arr = sorted(a_arr)

for i in range(N-1):
    if new_a_arr[i]==new_a_arr[i+1]:
        print("NO")
        break
    elif i==N-2:
        print("YES")
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10 ** 6)
n,q = map(int,input().split())
tree = [[] for _ in range(n)]
point = [0] * n

for _ in range(n-1):
    a,b = map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    
for _ in range(q):
    a,b = map(int,input().split())
    a -= 1
    point[a] += b
    
def dfs(now, prev = -1):
    for next in tree[now]:
        if next == prev:
            continue
        point[next] += point[now]
        
        dfs(next, now)
        
dfs(0)
print(*point)

### FIXED CODE ###

import sys
sys.setrecursionlimit(10 ** 6)
import sys
def input():
    return sys.stdin.readline()[:-1]

n,q = map(int,input().split())
tree = [[] for _ in range(n)]
point = [0] * n

for _ in range(n-1):
    a,b = map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)
    
for _ in range(q):
    a,b = map(int,input().split())
    a -= 1
    point[a] += b
    
def dfs(now, prev = -1):
    for next in tree[now]:
        if next == prev:
            continue
        point[next] += point[now]
        
        dfs(next, now)
        
dfs(0)
print(*point)
### BUGGY CODE ###

s = input()
checker = [False]*2019
checker[0]=True
res = 0
for i in range(1,len(s)+1):
    a = int(s[-i:]) % 2019
    if checker[a] == True:
        res += 1
    checker[a] = True
if int(s)%2019==0:
  	res+=1
print(res)

### FIXED CODE ###

s=input()

counter=[0]*2019
counter[0]=1
num=0
t=1
prefer=0
for i in reversed(s):
    num+=int(i)*t
    num%=2019
    t*=10
    t%=2019
    counter[num]+=1

ans=0
for i in range(2019):
    c=counter[i]
    ans+=c*(c-1)/2
print(int(ans))
### BUGGY CODE ###

N = int(input())
sequence = list(map(int, input().split()))
sequence.sort()

cnt = 0
pos = 0

while (pos < N):
    
    cur_value = sequence[pos]
    tmp_cnt = sequence.count(cur_value)
    
    if (tmp_cnt < cur_value):
        cnt += tmp_cnt
    else:
        cnt += tmp_cnt - cur_value
    
    pos += tmp_cnt

print(cnt)

### FIXED CODE ###

import collections

N = int(input())
sequence = list(map(int, input().split()))
CTR = collections.Counter(sequence).most_common()
ans = 0

for i in range(len(CTR)):
    cnt = CTR[i][1]
    obj = int(CTR[i][0])

    if (obj > cnt):
        ans += cnt
    
    else:
        ans += cnt - obj
    
print(ans)
### BUGGY CODE ###

N,K=map(int,input().split())
L=[]
for i in range(K):
    l,r=map(int,input().split())
    L.append([l,r+1])
L.sort()
mod=998244353
A=[0 for i in range(N+1)]
A[1]=1
for i in range(N+1):
    if A[i]>0:
        A[i]%=mod
        for l,r in L:
            for n in range(l+i,r+i):
                if n<=N:
                    A[n]+=A[i]
                else:
                    break
print(A[N]%mod)

### FIXED CODE ###

N,k=map(int,input().split())
L=[0 for i in range(2)]

K=[]
for i in range(k):
    l,r=map(int,input().split())
    K.append([l,r])
mod=998244353
L[1]=1
R=[0,1]
for i in range(2,N+1):
    cnt=0
    for l,r in K:
        cnt+=R[max(0,i-l)]
        cnt-=R[max(0,i-(r+1))]
    cnt%=mod
    L.append(cnt)
    R.append(R[-1]+cnt)
print(L[-1]%mod)
#print(R)
### BUGGY CODE ###

import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  s=S()
  f=True
  q=I()

  for _ in range(q):
    l=LS()
    if l==['1']:
      f=not f
    else:
      if l[1]=='1':
        if f:
          s=l[2]+s
        else:
          s+=l[2]
      else:
        if f:
          s+=l[2]
        else:
          s=l[2]+s

  if f:
    return s
  ans=list(s)
  ans.reverse()
  return ''.join(ans)

# main()
print(main())


### FIXED CODE ###

import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  s=list(S())
  s=collections.deque(s)
  f=True
  q=I()

  for _ in range(q):
    l=LS()
    if l==['1']:
      f=not f
    else:
      if l[1]=='1':
        if f:
          s.appendleft(l[2])
        else:
          s.append(l[2])
      else:
        if f:
          s.append(l[2])
        else:
          s.appendleft(l[2])

  s=list(s)

  if f:
    return ''.join(s)
  s.reverse()
  return ''.join(s)

# main()
print(main())
### BUGGY CODE ###

#import random

def putmx(lis):
  ret=[]
  mx=max(lis)
  for i in range(len(lis)):
    if mx==lis[i]:
      ret.append(i)
  return ret
  

h,w,m=map(int,input().split())
#inp=[(random.randrange(1,h+1),random.randrange(1,w+1)) for i in range(m)]
hb=[0]*h
wb=[0]*w
bmb=[-1]*h
for i in range(m):
  hh,ww=map(int,input().split())
  hh-=1
  ww-=1
  if bmb[hh]==-1:
    bmb[hh]=[ww]
  else:
    bmb[hh].append(ww)
  hb[hh]+=1
  wb[ww]+=1

hmx=putmx(hb)
wmx=putmx(wb)
mhb=max(hb)
mwb=max(wb)
#print(hb,wb,hmx,wmx)
fl=False
for i in hmx:
  for j in wmx:
    if not j in bmb[i]:
      print(mhb+mwb)
      fl=True
      break
  if fl:
    break
else:
  print(mhb+mwb-1)



### FIXED CODE ###

#import random

def putmx(lis,mx):
  ret=[]
  for (i,j) in zip(range(len(lis)),lis):
    if j==mx:
      ret.append(i)
  return ret
  

h,w,m=map(int,input().split())
hb=[0]*h
wb=[0]*w
bmb=[]
for i in range(h):
  bmb.append({-1})
for i in range(m):
  hh,ww=map(int,input().split())
  hh-=1
  ww-=1
  bmb[hh].add(ww)
  hb[hh]+=1
  wb[ww]+=1
mhb=max(hb)
mwb=max(wb)
hmx=putmx(hb,mhb)
wmx=set(putmx(wb,mwb))

#print(hb,wb,hmx,wmx)
fl=False
for i in hmx:
  if wmx|bmb[i]!=bmb[i]:
    print(mhb+mwb)
    break
else:
  print(mhb+mwb-1)

#print(hmx,wmx,bmb)