Problem:
 Score : 400 points    Problem Statement Takahashi has a string S consisting of lowercase English letters.  Starting with this string, he will produce a new one in the procedure given as follows.  The procedure consists of Q operations. In Operation i  (1 \leq i \leq Q) , an integer T_i is provided, which means the following:    If T_i = 1 : reverse the string S .    If T_i = 2 : An integer F_i and a lowercase English letter C_i are additionally provided.   If F_i = 1 : Add C_i to the beginning of the string S .  If F_i = 2 : Add C_i to the end of the string S .     Help Takahashi by finding the final string that results from the procedure.      Constraints  1 \leq |S| \leq 10^5  S consists of lowercase English letters.  1 \leq Q \leq 2 \times 10^5  T_i = 1 or 2 .  F_i = 1 or 2 , if provided.  C_i is a lowercase English letter, if provided.         Input Input is given from Standard Input in the following format:  S  Q  Query_1  :  Query_Q   In the 3 -rd through the (Q+2) -th lines, Query_i is one of the following:  1   which means T_i = 1 , and:  2  F_i  C_i   which means T_i = 2 .      Output Print the resulting string.        Sample Input 1 a
4
2 1 p
1
2 2 c
1      Sample Output 1 cpa  There will be Q = 4 operations. Initially, S is a .    Operation 1 : Add p at the beginning of S . S becomes pa .    Operation 2 : Reverse S . S becomes ap .    Operation 3 : Add c at the end of S . S becomes apc .    Operation 4 : Reverse S . S becomes cpa .    Thus, the resulting string is cpa .       Sample Input 2 a
6
2 2 a
2 1 b
1
2 2 c
1
1      Sample Output 2 aabc  There will be Q = 6 operations. Initially, S is a .    Operation 1 : S becomes aa .    Operation 2 : S becomes baa .    Operation 3 : S becomes aab .    Operation 4 : S becomes aabc .    Operation 5 : S becomes cbaa .    Operation 6 : S becomes aabc .    Thus, the resulting string is aabc .       Sample Input 3 y
1
2 1 x      Sample Output 3 xy

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]

def main():
    S = input()
    Q = int(input())
    query = [list(input().split()) for _ in range(Q)]
    
    
    
    mode = True
    forward = []
    back = []
    for qs in query:
        if qs[0] == "1":
            mode = not mode
            continue
        
        if mode:
            if qs[1] == "1": 
                forward.append(qs[2])
            else:
                back.append(qs[2])
        else:
            if qs[1] == "2": 
                forward.append(qs[2])
            else:
                back.append(qs[2])

    ans = "".join(reversed(forward)) + S + "".join(back)
    if mode:
        print(ans)
    else:
        print(ans[::-1])


if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque

S = deque(list(input().rstrip()))
Q = int(input())
Query = []

flag = 0

for _ in range(Q):
    Query.append(input().rstrip().split())

for i in Query:
    if i[0] == "1":
        flag += 1
    elif i[1] == "1":
        if flag % 2 == 0:
            S.appendleft(i[2])
        else:
            S.append(i[2])
    else:
        if flag % 2 == 0:
            S.append(i[2])
        else:
            S.appendleft(i[2])
if flag % 2 == 0:
    print("".join(list(S)))
else:
    print("".join(list(S))[::-1])

Solution (Python):
tailing = [input()]
heading = []
q_num = int(input())
is_reverse = False
for _ in range(q_num):
    query = [x for x in input().split()]
    if query[0] == '1':
        is_reverse = not is_reverse
    else:
        if (not is_reverse and query[1] == '2') or (is_reverse and query[1] == '1'):
            tailing.append(query[2])
        else:
            heading.append(query[2])
ans = ''.join(reversed(heading)) + ''.join(tailing)
print(ans if not is_reverse else ans[::-1])

Solution (Python):
S = input()
Q = int(input())

reverse = False
add = [[], []]

for _ in range(Q):
    query = list(input().split())
    if query[0] == "1":
        reverse = not reverse
    else:
        add[reverse ^ (int(query[1]) - 1)].append(query[2])

if reverse:
    ans = ''.join(add[1][::-1]) + S[::-1] + ''.join(add[0])
else:
    ans = ''.join(add[0][::-1]) + S + ''.join(add[1])
print(ans)

Solution (Python):
s = input()
q = int(input())
queries = []
for _ in range(q):
    queries.append(list(input().split()))

state = False
head = ''
tail = ''
for query in queries:
    if query[0] == '1':
        state = not state
    elif (query[1] == '1') ^ state:
        head = head + query[2]
    else:
        tail = tail + query[2]

head = head[::-1]
res = head + s + tail

if state:
    res = res[::-1]

print(res)

Solution (Python):
import sys

input = sys.stdin.readline

def gcd(a: int, b: int):
    """ https://cocodrips.hateblo.jp/entry/2014/03/05/143623
    """
    while b:
        a, b = b, a%b
    return a

def lcm(a: int, b: int):
    return a * b // gcd(a, b)


def main():
	
	S = input().rstrip()
	Q = int(input())
	
	
	
	rev = 0		
	
	DF = "" 
	DR = "" 
	for q in range(Q):
		tq = input().split()
		if tq[0]=="1":
			rev ^= 1
		else:
			T,F,C = tq
			if F=="1":
				
				if rev == 0:
					DF += C 
				else:
					DR += C 
			else:
				
				if rev == 0:
					DR += C 
				else:
					DF += C 
	
	
	if rev == False:
		res = DF[::-1] + S + DR
	else:
		res = DR[::-1] + S[::-1] + DF

	print(res)
	
if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines


def main():
    
    
    s = readline().strip()
    Q = int(readline())

    queue = deque(s)
    r = 0

    for _ in range(Q):
        t, *x = map(str, readline().split())
        if t == "1":
            r += 1
        else:
            f, c = x[0], x[1]
            if f == "1":
                if r % 2 == 0:
                    queue.appendleft(c)
                else:
                    queue.append(c)
            else:
                if r % 2 == 0:
                    queue.append(c)
                else:
                    queue.appendleft(c)

    ans = "".join(queue)
    if r % 2 == 0:
        print(ans)
    else:
        print(ans[::-1])


if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline

L = list(input().strip())
Q = int(input())
head = []
tail = []
rev = False
for i in range(Q):
    q = list(map(str, input().split()))
    if len(q) == 1:
        rev = not rev
    else:
        t, f, c = q
        if rev is False and f == '1':
            head.append(c)
        if rev is False and f == '2':
            tail.append(c)
        if rev is True and f == '1':
            tail.append(c)
        if rev is True and f == '2':
            head.append(c)

if rev:
    L.reverse()
    tail.reverse()
    ans = tail + L + head
else:
    head.reverse()
    ans = head + L + tail

print(''.join(ans))

Solution (Python):
S = input()
Q = int(input())

heads_min_idx = 0
heads_max_idx = 0
tails_min_idx = 0
tails_max_idx = 0
heads = {}
tails = {}
rev_flag = 1  
for q in range(Q):
    tmp_q = input()
    if tmp_q == '1':
        rev_flag *= -1
    else:
        _, f, c = tmp_q.split()
        if rev_flag == 1:
            if f == '1':
                heads[heads_min_idx - 1] = c
                heads_min_idx -= 1
            else:
                tails[tails_max_idx + 1] = c
                tails_max_idx += 1
        else:
            if f == '1':
                tails[tails_max_idx + 1] = c
                tails_max_idx += 1
            else:
                heads[heads_min_idx - 1] = c
                heads_min_idx -= 1

if rev_flag == 1:
    head_str = ''.join([s for _, s in sorted(heads.items(), key=lambda x: x[0])])
    tail_str = ''.join([s for _, s in sorted(tails.items(), key=lambda x: x[0])])
    print(head_str + S + tail_str)
else:
    head_str = ''.join([s for _, s in sorted(tails.items(), key=lambda x: x[0], reverse=True)])
    tail_str = ''.join([s for _, s in sorted(heads.items(), key=lambda x: x[0], reverse=True)])
    print(head_str + S[::-1] + tail_str)

Solution (Python):
from collections import deque

S = list(input())
Q = int(input())

d = deque(S)

hd = []
bc = []
cnt = 0
mm = 0

for i in range(Q):
    q = list(input().split())

    if q[0]=="1":
        cnt += 1
    





    elif q[0]=="2":
        f = int(q[1])
        c = q[2]
        mm += 1

        if (f+cnt)%2==0:
            d.append(c)
        else:
            d.appendleft(c)

if cnt%2==0:
    for i in range(len(S)+mm):
        
        print(d.popleft(),end='')
else:
    for i in range(len(S)+mm):
        print(d.pop(),end='')
print()

Solution (Python):
from collections import deque
s=input()
q=int(input())
rev=0
head=deque()
tail=deque()
for _ in range(q):
    Q=input().split()
    if len(Q)==1:
        rev=1-rev
    if len(Q)==3:
        if(rev==0 and Q[1]=="1" )or (rev==1 and Q[1]=="2"):
            head.appendleft(Q[2])
        else :
            tail.append(Q[2])
if rev==0:
    ans="".join(head)+s+"".join(tail)

else:
    ans="".join(tail)[::-1]+s[::-1]+"".join(head)[::-1]

print(ans)

Solution (Python):

from collections import deque


s = deque(list(input()))
q = int(input())

reverce = False
for _ in range(q):
    query = input()
    if query[0] == '1':
        reverce = not reverce
    else:
        _, f, c = query.split()
        if (f == '1' and not reverce) or (f == '2' and reverce):
            s.appendleft(c)
        else:
            s.append(c)

if reverce:
    s.reverse()

print("".join(s))

Solution (Python):
s=input()
q=int(input())
f=0
l,r='',''
for i in range(q):
    a=list(input().split())
    if a[0]=='1':
        f+=1
    else:
        if (int(a[1])-1)^(f%2)==0:
            l+=a[2]
        else:
            r+=a[2]
if f%2==1:
    print(r[::-1]+s[::-1]+l)
else:
    print(l[::-1]+s+r)

Solution (Python):
from collections import deque
def main():
    S=input()
    S=deque(S)
    Q=int(input())
    flag=1
    for _ in range(Q):
        q=input()
        if q=="1":
            flag*=-1
            continue
        q=list(q.split(" "))
        q[1]=int(q[1])
        if q[1]==2:
            q[1]=-1
        if q[1]*flag <=0:
            S.append(q[2])
        else:
            S.appendleft(q[2])
    if flag==1:
        print("".join(list(S)))
    else:
        print("".join(list(S)[::-1]))
            

main()

Solution (Python):
from collections import deque
s = list(input())
ans = deque(s)
Q = int(input())
is_reverse = False
for _ in range(Q):
    q = list(map(str,input().split()))
    if q[0] == '1':
        is_reverse = True ^ is_reverse 
        
    else:
        if is_reverse: 
            if q[1] == '1':
                
                ans.append(q[2])
            else:
                
                ans.appendleft(q[2])
        else:
            if q[1] == '1':
                
                ans.appendleft(q[2])
            else:
                
                ans.append(q[2])
ans_s = ''.join(ans)
if is_reverse:
    print(ans_s[::-1])
else:
    print(ans_s)

Solution (Python):
S = input()
Q = int(input())
cnt = 0
l = ''
r = ''
for i in range(Q):
    tmp = list(map(str,input().split()))
    if len(tmp) == 1:
        cnt += 1
    else:
        if cnt % 2 == 0:
            if tmp[1] == '1':
                l = l + tmp[2]
            else:
                r = r + tmp[2]
        else:
            if tmp[1] == '1':
                r = r + tmp[2]
            else:
                l = l + tmp[2]
if cnt % 2 == 0:
    ans = l[::-1] + S + r
else:
    ans = r[::-1] + S[::-1] + l
print(ans)

Solution (Python):
from collections import deque

S = deque(input())
q = int(input().strip())


rev_count = 0
for i in range(q):
  query = input()
  if query[0] == "1":
    rev_count += 1
  elif query[0] == "2":
    query = query.strip().split(" ")
    if rev_count & 1 == 1:
      if query[1] == "1":
        S.append(query[2])
      else:
        S.appendleft(query[2])
    else:
      if query[1] == "1":
        S.appendleft(query[2])
      else:
        S.append(query[2])

if rev_count & 1 == 1:
  S.reverse()

print("".join(S))

Solution (Python):
import sys, math
def input():
    return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial
from bisect import bisect_left 

enu = enumerate

sys.setrecursionlimit(10**7)
S = input()
Q = int(input())
Que = [input().split() for _ in range(Q)]

d = deque([s for s in S])

oneisleft = True
for q in Que:
    if q[0] == '1':
        oneisleft = not(oneisleft)
    else:
        fi, ci = q[1], q[2]
        if oneisleft:
            if fi == '1':
                d.appendleft(ci)
            else:
                d.append(ci)
        else:
            if fi == '1':
                d.append(ci)
            else:
                d.appendleft(ci)
if oneisleft:
    res = ''.join(list(d))
else:
    res = ''.join(reversed(list(d)))
print(res)

Solution (Python):
s = list(input())
q = int(input())

revs = 0
front = []
rear = []

for i in range(q):
    ins = input().split()
    if(ins[0] == "1"):
        revs += 1
    else:
        if (ins[1] == "1" and revs%2 == 0 or ins[1] =="2" and revs%2 == 1):
            front.extend(ins[2])
        else:
            rear.extend(ins[2])

if (revs % 2 == 0):
    for j in reversed(front):
        print(j, end="")
    for j in s:
        print(j, end="")
    for j in rear:
        print(j, end="")
else:
    for j in reversed(rear):
        print(j, end="")
    for j in reversed(s):
        print(j, end="")
    for j in front:
        print(j, end="")
print()

Solution (Python):
def main():
    S = input()
    Q = int(input())
    count = 0
    A = []
    B = []
    for _ in range(Q):
        U = input()
        if len(U) == 1:
            count += 1
        else:
            _, F, C = U.split()
            F = int(F)
            if F == 1:
                if count % 2 == 0:
                    A.append(C)
                else:
                    B.append(C)
            else:
                if count % 2 == 0:
                    B.append(C)
                else:
                    A.append(C)

    if count % 2 == 0:
        A = A[::-1]
        return "".join(A) + S + "".join(B)
    else:
        B = B[::-1]
        return "".join(B) + S[::-1] + "".join(A)
        
if __name__ == '__main__':
    print(main())

Solution (Python):
s = input()
q = int(input())

reverse_flag = 0
head = ""
back = ""
for _ in range(q):
    query = input()
    if query[0] == "1":
        reverse_flag ^= 1
    else:
        t,f,c = query.split()
        f = int(f) + reverse_flag
        if f%2 == 1:
            head = c + head
        else:
            back = back + c
s = head + s + back
print(s if reverse_flag%2 == 0 else s[::-1])

Solution (Python):
s = input()
q = int(input())
p = 1
start = ""
end = ""
query =[]
for i in range(q):
    a = list(map(str,input().split()))
    query.append(a)

for i in range(q):
    if int(query[i][0]) == 1:
        p = p * (-1)
    else:
        if int(query[i][1]) == 1:
            if p ==1:
                start = query[i][2] + start
            else:
                end = query[i][2] + end
        else:
            if p == 1:
                end = query[i][2] + end
            else:
                start = query[i][2] + start
if p == 1:
    ans = start + s + end[::-1]
else:
    ans = end + s[::-1] + start[::-1]
print(ans)

Solution (Python):
from collections import deque

S = input()
Q = int(input())
d = deque()
for s in S:
    d.append(s)
cnt = 0
for _ in range(Q):
    q = input().split()
    if q[0] == '1':
        cnt += 1
    else:
        if q[1] == '1':
            if cnt & 1:
                d.append(q[2])
            else:
                d.appendleft(q[2])
        else:
            if cnt & 1:
                d.appendleft(q[2])
            else:
                d.append(q[2])
if cnt & 1:
    ans = reversed(list(d))
else:
    ans = list(d)
print(''.join(ans))

Solution (Python):
from collections import deque

def answer():
    s = deque(input())
    q = int(input())
    rev = False
    for i in range(q):
        query = input().split()
        if int(query[0]) == 2:
            f, c = int(query[1]), query[2]
            if (not rev and f == 1) or (rev and f == 2):
                s.appendleft(c)
            else:
                s.append(c)
        else:
            rev = not rev
    if rev:
        s = list(s)
        s = s[::-1]
    print(''.join(s))
    return

answer()

Solution (Python):
from collections import deque

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

reverse_flag = -1 

for i in range(q):
    query = list(input().split())
    if query[0] == '1':
        reverse_flag *= -1
    else:
        if query[1] == '1':
            if reverse_flag == -1:
                deque.appendleft(s, query[2])
            else:
                deque.append(s, query[2])
        else:
            if reverse_flag == -1:
                deque.append(s, query[2])
            else:
                deque.appendleft(s, query[2])
                
if reverse_flag == 1:
    s.reverse()
    
print(''.join(s))

Solution (Python):
from collections import deque

mae = deque()
usiro=deque()

s=input()
kai=int(input())

siji=[]*kai

for i in range(kai):
    siji.append(input())


state=1
for i in range(kai):
    si=siji[i]
    if(si[0]=='1'):
        state*=-1
    else:
        _,f,c=si.split()
        f=int(f)
        if(state==-1):
            f=3-f
        if(f==1):
            mae. appendleft(c)
        else:
            usiro.append(c)

ans=deque()
for m in mae:
    if(state==1):
        ans.append(m)
    else:
        ans.appendleft(m)
for smoji in s:
    if(state==1):
        ans.append(smoji)
    else:
        ans.appendleft(smoji)
for u in usiro:
    if(state==1):
        ans.append(u)
    else:
        ans.appendleft(u)

kotae="".join(ans)
print(kotae)

Solution (Python):
from collections import deque
S = input()
Q = int(input())
left = deque()
right = deque()
rotate = 1
for i in range(Q):
    n = [str(i) for i in input().split()]
    if n[0] == "1":
        rotate *= -1
    else:
        if n[1] == "1":
            if rotate == 1:
                left.appendleft(n[2])
            else:
                right.append(n[2])
        else:
            if rotate == 1:
                right.append(n[2])
            else:
                left.appendleft(n[2])
left = list(left)
right = list(right)
ans = "".join(left)
ans += S
ans += "".join(right)
if rotate == 1:
    print(ans)
else:
    print(ans[::-1])

Solution (Python):
s=input()
q=int(input())
dp=[' ']*(len(s))
for i in range(len(s)):
    dp[i]=s[i]
index=[0]*(len(s))
for i in range(len(s)):
    index[i]=i
flag=0
head=-1
tail=len(s)
for i in range(q):
    t=input()
    if t[0]=='1':
        flag=1-flag
    else:
        _,f,c=map(str,t.split())
        dp.append(c)
        if f=='1':
            if flag==1:
                index.append(tail)
                tail+=1
            else:
                index.append(head)
                head-=1
        else:
            if flag==0:
                index.append(tail)
                tail+=1
            else:
                index.append(head)
                head-=1
index2=[]
for i in range(len(dp)):
    index2.append((index[i],dp[i]))
index2.sort(reverse=flag)

for i in range(len(index)):
    print(index2[i][1],end='')

Solution (Python):
s=input()
q=int(input())

rev=0

sento=[]
matsubi=[]

for _ in range(q):
    temp=input().split(" ")
    
    if temp[0]=="1":
        if rev==0:
            rev=1
        else:
            rev=0
    else:
        if rev==0:
            if temp[1]=="1":
                sento.append(temp[2])
            else:
                matsubi.append(temp[2])
        else:
            if temp[1]=="2":
                sento.append(temp[2])
            else:
                matsubi.append(temp[2])

sento_s="".join(sento)
sento_s=sento_s[::-1]
matsubi_s="".join(matsubi)

s=sento_s+s+matsubi_s

if rev==0:
    print(s)
else:
    print(s[::-1])

Solution (Python):
S = input()
Q = int(input())
bgn = ''
end = ''
is_inversion = False

for _ in range(Q):
    query = input().split()
    if query[0] == '1':
        if is_inversion:
            is_inversion = False
        else:
            is_inversion = True
    elif query[0] == '2':
        if query[1] == '1':
            if is_inversion:
                end += query[2]
            else:
                bgn += query[2]
        elif query[1] == '2':
            if is_inversion:
                bgn += query[2]
            else:
                end += query[2]
    


if is_inversion:
    ans = end[::-1] + S[::-1] + bgn
else:
    ans = bgn[::-1] + S + end

print(ans)

Solution (Python):
s = input()
q = int(input())

conv = 0
pre = []
pos = []
for i in range(q):
    query = input().split()
    if query[0] == '1':
        conv += 1
        continue
    if (int(query[1])+conv) %2 == 1:
        pre.append(query[2])
        continue
    pos.append(query[2])
if conv % 2 == 0:
    pre = ''.join(pre[::-1])
    pos = ''.join(pos[::1])
    s = pre + s + pos
else:
    pre = ''.join(pre[::1])
    pos = ''.join(pos[::-1])
    s = s[::-1]
    s = pos + s + pre
print(s)

Solution (Python):
s = input()
q = int(input())

sei_or_gyaku = 1
mae = ''
ato = ''

for i in range(q):
    sirei = input()
    if len(sirei) == 1:
        ti = int(sirei)
        sei_or_gyaku *= -1
    else:
        ti, fi, ci = map(str, sirei.split())
        ti, fi = int(ti), int(fi)
        if fi == 1:
            if sei_or_gyaku == 1:
                mae += ci
            else:
                ato += ci
        else:
            if sei_or_gyaku == 1:
                ato += ci
            else:
                mae += ci

mae = mae[::-1]
ans = mae + s + ato
if sei_or_gyaku == 1:
    print(ans)
else:
    print(ans[::-1])

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
sys.setrecursionlimit(10 ** 7)

reverse = 0
pre = []
after = []
S = input()
Q = int(input())
for i in range(Q):
    q = input()
    if q[0] == '1':
        reverse = 1 - reverse
    else:
        T, F, C = q.split()
        if (F == '1') ^ (reverse == 1):
            pre.append(C)
        else:
            after.append(C)
if reverse:
    after.reverse()
    ans = ''.join(after) + S[::-1] + ''.join(pre)
else:
    pre.reverse()
    ans = ''.join(pre) + S + ''.join(after)
print(ans)

Solution (Python):



from fractions import gcd 
from functools import reduce
import sys
sys.setrecursionlimit(200000000)
from inspect import currentframe




def printargs2err(*args):
    names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???')+' : '+repr(arg) for arg in args),file=sys.stderr)
def debug(*args):
    print(*args,file=sys.stderr)

def printglobals():
    for (symbol, value) in globals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
def printlocals():
    for (symbol, value) in locals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)

def pin(type=int):
    return map(type,input().split())
     

from collections import deque
import sys
def resolve():
    S=deque(input())
    Q,=pin()
    ans=""
    turn=0
    for i in range(Q):
        q=sys.stdin.readline().rstrip().split()
        if q[0]=="1":turn=(turn+1)%2
        else:
            f=int(q[1])%2
            if f!=turn:
                S.appendleft(q[2])
            else:
                S.append(q[2])
    if turn==1:S.reverse()
    for s in S:
        ans+=s
    print(ans)
    


"""


"""
"""
お前カッコ閉じるの忘れてるだろ
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """a
4
2 1 p
1
2 2 c
1"""
        output = """cpa"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """a
6
2 2 a
2 1 b
1
2 2 c
1
1"""
        output = """aabc"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """y
1
2 1 x"""
        output = """xy"""
        self.assertIO(input, output)

if __name__=="__main__":resolve()

Solution (Python):
s = input()
q = int(input())

tmp = 1
a = ''
b = ''
for _ in range(q):
    query = input().split()
    if query[0] == '1':
        tmp *= -1
    else:
        if tmp > 0:
            if query[1] == '1':
                a = ''.join((query[2], a))
            else:
                b = ''.join((b, query[2]))
        else:
            if query[1] == '1':
                b = ''.join((b, query[2]))
            else:
                a = ''.join((query[2], a))
res = ''.join((a, s, b))
if tmp > 0:
    print(res)
else:
    print(res[::-1])

Solution (Python):


s = input()
q = int(input())
qs = [list(input().split()) for i in range(q)]

pls_vec = []
pls_append = pls_vec.append

mns_vec = []
mns_append = mns_vec.append

q1_vec = 1
for qi in qs:
    if qi[0]=="1":
        q1_vec*=(-1)
    else:
        if q1_vec==1:
            if qi[1]=="1":
                mns_append(qi[2])
            else:
                pls_append(qi[2])
        else:
            if qi[1]=="1":
                pls_append(qi[2])
            else:
                mns_append(qi[2])

ret = "".join(mns_vec[::-1]) + s + "".join(pls_vec)
if q1_vec==-1:
    ret=ret[::-1]
print(ret)

Solution (Python):
import math
from collections import deque
def main():
    s = deque(input())
    q = int(input())

    counter = 0
    for _ in range(q):
        query = [t for t in input().split()]
        if len(query)==1:
            counter +=1

        else:
            f = (counter+int(query[1]))%2
            if f==1:
                s.appendleft(query[2])
            else:
                s.append(query[2])

    s = list(s)
    if counter%2==1:
        s = s[::-1]

    for c in s:
        print(c,end='')

    print()


if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import defaultdict, Counter, deque
from itertools import accumulate, permutations, combinations
from operator import itemgetter
from bisect import bisect_left, bisect_right, bisect
from heapq import heappop, heappush
from fractions import gcd
from math import ceil, floor, sqrt, cos, sin, pi
from copy import deepcopy




def main():
    S = input()
    Q = int(input())
    head = ""
    tail = ""
    is_vert_normal = True
    for _ in range(Q):
        query = input().split()
        T = int(query[0])
        if T == 1:
            is_vert_normal = not is_vert_normal
        else:
            F = int(query[1])
            C = query[2]
            if F == 1:
                if is_vert_normal:
                    head += C
                else:
                    tail += C
            else:
                if not is_vert_normal:
                    head += C
                else:
                    tail += C
    if is_vert_normal:
        print(head[::-1] + S + tail)
    else:
        print(tail[::-1] + S[::-1] + head)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
s = deque(input())
q = int(input())
isRight = True
for i in range(q):
    query = input()
    if query[0] == '1':
        isRight = not(isRight)
    else:
        _, f, c = query.split()
        if f == '1':
            if isRight:
                s.appendleft(c)
            else:
                s.append(c)
        else:
            if isRight:
                s.append(c)
            else:
                s.appendleft(c)
t = ''.join(list(s))
if not isRight:
    reversed(t)
print(t if isRight else t[::-1])

Solution (Python):



def main():
  s = input().strip()
  q = int(input())
  state = 1
  swap = [0, 2, 1]
  ss = []
  es = []
  for _ in range(q):
    x = input().strip()
    if x == '1':
      state *= -1
    else:
      _, f, c = x.split(' ')
      f = int(f)
      if state == -1:
        f = swap[int(f)]
      if f == 1:
        ss.append(c)
      else:
        es.append(c)
  s = ''.join(ss[::-1]) + s + ''.join(es)
  if state == -1:
    s = s[::-1]
  print(s)

if __name__=='__main__':
  main()

Solution (Python):
s = input()
q = int(input())
 
rev = False
fore = []
end = []
 
for i in range(q):
    l = input().split()
    if l[0] == "1":
        rev ^= True
    else:
        if l[1] == "1":
            if rev == False:
                fore.append(l[2])
            else:
                end.append(l[2])
        else:
            if rev == False:
                end.append(l[2])
            else:
                fore.append(l[2])
 
if rev == False:
    print("".join(reversed(fore)) + s + "".join(end))
else:
    print("".join(reversed(end)) + "".join(reversed(s)) + "".join(fore))

Solution (Python):
from collections import defaultdict, Counter, namedtuple, deque
from bisect import bisect_left
from functools import reduce
import math

NN = 2020202
MOD = 10**9+7
INF = float("inf")


S = list(input().split())
Q = int(input())
query = [list(input().split()) for i in range(Q)]
que = deque(S)
rev = 0

for q in query:
    if len(q) == 1:
        rev ^= 1
    else:
        if q[1] == "1":
            if rev:
                que.append(q[2])
            else:
                que.appendleft(q[2])
        else:
            if rev:
                que.appendleft(q[2])
            else:
                que.append(q[2])
    

if rev:
    print("".join(que)[::-1])
else:
    print("".join(que))

Solution (Python):
s = input()
q = int(input())
rev = 0
head = []
tail = []
is_rev = False

for _ in range(q):
    qq = input().split()
    t = int(qq[0])
    if t == 1:
        rev += 1
        is_rev = not is_rev
    else:
        f = int(qq[1])
        c = qq[2]
        if f == 1:
            if is_rev:
                tail.append(c)
            else:
                head.append(c)
        else:
            if is_rev:
                head.append(c)
            else:
                tail.append(c)

if is_rev:
    ls = list(reversed(tail))
    ls.extend(reversed(s))
    ls.extend(head)
else:
    ls = list(reversed(head))
    ls.extend(s)
    ls.extend(tail)
print(''.join(ls))

Solution (Python):
import sys
fastinput = sys.stdin.readline
from collections import deque
S = input()
Q = int(input())
ans = deque([S])
Reverse = False
for q in range(Q):
    query = fastinput().split()
    if query[0]=="1":
        Reverse = not Reverse
    elif (query[1]=="1") ^ Reverse:
        ans.appendleft(query[2])
    else:
        ans.append(query[2])
SS = "".join(list(ans))
if Reverse:
    SS = "".join(reversed(SS))
print(SS)

Solution (Python):
S = input()
Q = int(input())

prefix = ''
suffix = ''
mode = 0
for _ in range(Q) :
  Query = list(input().split())
  if Query[0] == '1' :
    mode ^= 1
  else :
    _, F, C = Query
    F = int(F) - 1
    
    if mode != F :
      suffix += C
    else :
      prefix += C
      

if mode == 0 :
  print(prefix[::-1] + S + suffix)
else :
  print(suffix[::-1] + S[::-1] + prefix)

Solution (Python):
S = input()
N = int(input())
Q = [input().split() for _ in range(N)]
start = ''
end = ''


direct = 0
for i in range(N):
  if Q[i][0] =='1':
    direct^=1
  else:
    if direct == int(Q[i][1])-1:
      start += Q[i][2]
    else:
      end += Q[i][2]
      
ans = start[::-1]+S+end
print(ans) if direct == 0 else print(ans[::-1])