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



Sample input:
a
4
2 1 p
1
2 2 c
1


Sample output:
cpa

Submission status: Accepted

Solution code:
from collections import deque

S = list(input())
s = deque(S)
q = int(input())
Q = [list(input().split()) for _ in range(q)]

rev = 0
for i in range(q):
    if len(Q[i]) == 1:
        rev += 1
        rev %= 2
    else:
        if rev == 0:
            if Q[i][1] == "1":
                s.appendleft(Q[i][2])
            else:
                s.append(Q[i][2])
        else:
            if Q[i][1] == "2":
                s.appendleft(Q[i][2])
            else:
                s.append(Q[i][2])

s = list(s)
if rev == 0:
    for i in range(len(s)):
        print(s[i],end="")
else:
    for i in reversed(range(len(s))):
        print(s[i],end="")
print()

Submission status: Accepted

Solution code:
#coding:utf-8
import sys,os
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    XLMIIS = lambda x: [LMIIS() for _ in range(x)]
    YN = lambda c : print('Yes') if c else print('No')
    MOD = 10**9+7
    S = input()
    Slist = [S]
    Q = II()
    Slist = ['']*Q+Slist+['']*Q
    left = Q-1
    right = Q+1
    r = False
    for _ in range(Q):
        query = input().split()
        if query[0] == '1':
            r ^= True
        else:
            if query[1] == '1':
                    if r:
                        # S = ''.join([S,query[2]])
                        Slist[right] = query[2]
                        right += 1

                    else:
                        # S = ''.join([query[2],S])
                        Slist[left] = query[2]
                        left -=1
            else:
                if r:
                    Slist[left] = query[2]
                    left -=1
                else:
                    # S = ''.join([S,query[2]])
                    Slist[right] = query[2]
                    right += 1
    # print(S[::-1] if r else S)
    if r:
        Slist[Q] = Slist[Q][::-1]

    print(''.join(Slist[::-1]) if r else ''.join(Slist))
                



    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

#import numpy as np
s = input()
n = int(input())
#qt = np.ones((n),dtype=np.int32)
#qf = np.zeros((n),dtype=np.int64)
#qc = [''] * n

mode = False
#mode = True : f1->s=c+s,f2->s=s+c
#mode = False : f1->s=s+c,f2->s=c+s

front = ''
back = ''
for i in range(n):
    qs = input()
    if len(qs) == 1:
        mode = not mode
        #s = s[::-1]
        #pass
    else:
        #qt[i] = 2
        #qf[i] = int(qs[1:-2])
        #qc[i] = qs[-1]
        if not mode:
            if int(qs[2]) == 1:
                front += qs[4]
                #s = qs[4] + s
            else:
                back += qs[4]
                #s = s + qs[4]
        else:
            if int(qs[2]) == 1:
                back += qs[4]
                #s = s + qs[4]
            else:
                front += qs[4]
                #s = qs[4] + s


#print(mode,front,back)
#hanten
if mode:
    print(back[::-1] + s[::-1] + front)
#no hanten
else:
    print(front[::-1] + s + back)

Submission status: Accepted

Solution code:
import math

s = input()
q = int(input())
reverse_flag = 0
head = ""
tail = ""

for i in range(q):
  query = input().split(" ")
  if(len(query) == 1):
    reverse_flag += 1
  else:
    if((reverse_flag + int(query[1])) % 2 == 0):
      tail += query[2]
    else:
      head = query[2] + head

ans_str = head + s + tail

if(reverse_flag % 2 == 1): print(ans_str[::-1])
else: print(ans_str)

Submission status: Accepted

Solution code:
s = input()
Q = int(input())
count = 0
right = []
left = []
for i in range(Q):
    q = input().split()
    if int(q[0]) == 1:
        count += 1
    else:
        if count%2 == 0:
            if int(q[1]) == 1:
                left.append(q[2])
            else:
                right.append(q[2])
        else:
            if int(q[1]) == 1:
                right.append(q[2])
            else:
                left.append(q[2])

left = "".join(left)
right = "".join(right)
if count%2 == 0:
    left = left[::-1]
    print(left+s+right)
else:
    s = s[::-1]
    right = right[::-1]
    print(right+s+left)

Submission status: Accepted

Solution code:
*s, = input()
_q = int(input())
rev = 0
l, r = [], []
for _ in range(_q):
    *q, = map(str, input().split())

    if q[0] == "1":
        rev += 1
        continue

    t = q[0]
    f = q[1]
    c = q[2]

    if rev%2 == 0:
        if f == "1":
            l.append(c)
        else:
            r.append(c)
    else:
        if f == "1":
            r.append(c)
        else:
            l.append(c)

*l, = reversed(l)

s = l + s + r

if rev%2 == 1:
    *s, = reversed(s)

print("".join(s))

Submission status: Accepted

Solution code:
from collections import deque
s = input()
q = int(input())

header = []
footer = []
flag = 0
for i in range(q):
    x = list(input().split())
    if int(x[0]) == 1:
        if flag ==0:
            flag = -1
        else:
            flag = 0
        continue
    if int(x[1]) +flag == 1:
        header.append(x[2])
        # s2 = deque(s)
        # # s.insert(0, x[2])
        # s2.appendleft(x[2])
        # s = list(s2)
    else:
        # s.append(x[2])
        footer.append(x[2])
# ans = ''.join(s)
head = ''.join(reversed(header))
ans = head +s + ''.join(footer)
if flag == -1:
    print(ans[::-1])
else:
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
ss = input()
s = []
for i in range(0, len(ss)):
    s.append(ss[i])
n = int(input())
mae_list = []
usiro_list = []
flag = 1
for i in range(0, n):
    q_list = list(map(str, input().split()))
    if len(q_list) == 1:
        flag *= -1
    else:
        if (q_list[1] == "1" and flag == 1) or (q_list[1] == "2" and flag == -1):
            mae_list.append(q_list[2])
        else:
            usiro_list.append(q_list[2])
if flag == 1:
    if len(mae_list) > 0:
        mae_list.reverse()
        print(''.join(mae_list), end="")
    print(''.join(s), end="")
    if len(usiro_list) > 0:
        print(''.join(usiro_list), end="")
else:
    if len(usiro_list) > 0:
        usiro_list.reverse()
        print(''.join(usiro_list), end="")
    s.reverse()
    print(''.join(s), end="")
    if len(mae_list) > 0:
        print(''.join(mae_list), end="")
print()

Submission status: Accepted

Solution code:
from collections import deque

S = input()
Q = int(input())
flag_reversed = False
ret = deque(S)

for _ in range(Q):
    temp = input()
    if (len(temp) < 2):
        flag_reversed = not flag_reversed
    else:
        T, F, C = [x for x in temp.split(" ")]
        F = int(F)
        add_begin = True
        if (F == 2):
            add_begin = False
        if (flag_reversed):
            add_begin = not add_begin
        if (add_begin):
            ret.appendleft(C)
        else:
            ret.append(C)

ret = ''.join(ret)

if (flag_reversed):
    ret = ''.join(reversed(ret))
print(ret)

Submission status: Accepted

Solution code:
from collections import deque

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

roll = False
ans = deque([s])
preNum = 0

for i in range(q) :
    inp = input()
    if inp[:1] == '1' :
        roll = not roll
        #print(roll)
    else :
        t, f, c = inp.split()
        #print(ans)
        #print(t, f, c)
        if (f == '1' and (not roll)) or (f == '2' and roll) :
            ans.appendleft(c)
            preNum += 1
        else :
            ans.append(c)
#print(ans)
ans = list(ans)
if roll :
    ans[preNum] = ans[preNum][::-1]
    ans = ans[::-1]

#print(ans)
#print("".join(ans))
for s in ans :
    print(s, end='')

Submission status: Accepted

Solution code:
from collections import deque
S = input()
Q = int(input())
pre = deque()
suf = deque()
rev = False
for i in range(Q):
    q = input().split()
    if len(q) == 1:
        rev = not rev
    else:
        if (not rev and q[1] == '1') or (rev and q[1] == '2'):
            pre.appendleft(q[2])
        else:
            suf.append(q[2])
if rev:
    S = S[::-1]
    p = list(suf)[::-1]
    s = list(pre)[::-1]
else:
    p = list(pre)
    s = list(suf)
print(''.join(p) + S + ''.join(s))

Submission status: Accepted

Solution code:
s=input()
q=int(input())
mode=1
h=[]
t=[]
for i in range(q):
    x=input()
    if x=="1":
        if mode==1:
            mode=0
        else:
            mode=1
    else:
        a=int(x[0])
        b=int(x[2])
        c=x[4]
        if b==1:
            if mode==1:
                h.append(c)
            else:
                t.append(c)
        elif b==2:
            if mode==0:
                h.append(c)
            else:
                t.append(c)
s=list(s)
if mode==1:
    ans=h[::-1]+s+t
elif mode==0:
    ans=t[::-1]+s[::-1]+h
print("".join(ans))

Submission status: Accepted

Solution code:
def main():
    from sys import stdin
    from collections import deque
    S = input()
    Q = int(input())
    reverse = 0
    head = []
    tail = []
    head_deque = deque(head)
    tail_deque = deque(tail)
    
    for _ in [0] * Q:
        readline = stdin.readline
        s = readline().split()
        if int(s[0]) == 1:
            if reverse == 1:
                reverse = 0
            else:
                reverse = 1
        else:
            if int(s[1]) == 1:
                if reverse == 1:
                    tail.append(s[2])
                else:
                    head_deque.appendleft(s[2])
            else:
                if reverse == 1:
                    head_deque.appendleft(s[2])
                else:
                    tail.append(s[2])
    head = list(head_deque)
    head = ''.join(head)
    tail = ''.join(tail)
    if reverse == 1:
        print(tail[::-1]+S[::-1]+head[::-1])
    else:
        print(head+S+tail)
        
main()

Submission status: Accepted

Solution code:
S = list(input())
Q = int(input())
is_reversed = False
append_first = []
my_first = append_first.append
append_end = []
my_end = append_end.append

for i in range(Q):
  q = list(input())
  if q[0] == '1':
    is_reversed = True if is_reversed == False else False
  else:
    if q[2] == '1' and is_reversed:
      append_end.append(q[4])
    elif q[2] == '1': 
      append_first.append(q[4])
    elif is_reversed:
      append_first.append(q[4])   
    else:
      append_end.append(q[4])
      
append_first.reverse()
append_first.extend(S) 
append_first.extend(append_end)

if is_reversed:
  append_first.reverse()
print(''.join(append_first))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	SS = input()
	SS = SS[:-1]
	Q = inputInt()

	mae = ""
	mae_to = []
	usiro = ""
	usiro_to = []

	flg = True
	for _ in range(Q):
		inp = input()
		inp = inp[:-1]
		inpt = inp.split()

		if len(inpt) == 1:
			if flg == True:
				flg = False
			else:
				flg = True
		else:
			oder = inpt[1]
			if oder == "1":
				if flg == True:
					mae = inpt[2] + mae
					if len(mae) > 10000:
						mae_to = [mae] + mae_to
						mae = ""
				else:
					usiro = usiro + inpt[2]
					if len(usiro) > 10000:
						usiro_to.append(usiro)
						usiro = ""
			else:
				if flg == True:
					usiro = usiro + inpt[2]
					if len(usiro) > 10000:
						usiro_to.append(usiro)
						usiro = ""
				else:
					mae = inpt[2] + mae
					if len(mae) > 10000:
						mae_to = [mae] + mae_to
						mae = ""

	#print(S)
	#S = "".join(S)
	usi = ""
	if len(usiro_to) > 0:
		usi = "".join(usiro_to) + usiro
	else:
		usi = usiro

	me = ""
	if len(mae_to) > 0:
		me = mae + "".join(mae_to)
	else:
		me = mae

	S = me + SS + usi

	if flg == True:
		print(S)
	else:
		print(S[::-1])


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# special thanks :
#  https://nagiss.hateblo.jp/entry/2019/07/01/185421
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
S = input()
Q = int(input())

count = True
ans = S

ireru_mae = ''
ireru_usiro = ''
for i in range(Q):
    T = input().split()
    if len(T)==1:
        count = not(count)
        ans = ireru_mae + ans + ireru_usiro
        ireru_mae = ''
        ireru_usiro = ''
        continue

    if count:
        if T[1] == '1': ireru_mae = T[2] + ireru_mae
        else: ireru_usiro += T[2]
    else:
        if T[1] == '1': ireru_usiro += T[2]
        else: ireru_mae = T[2] + ireru_mae

ans = ireru_mae + ans + ireru_usiro
if count:
    print(ans)
else:
    print(ans[::-1])

Submission status: Accepted

Solution code:
from collections import deque

head = deque()
tail = deque()
count_rev = 0
switch = 0

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

for i in range(Q):
    q = input()
    if(q == '1'):
        count_rev += 1
        if(switch == 1):
            switch = 0
        else:
            switch = 1

    else:
        tmp, f, c = q.split()
        if(f == '1'):
            # put head
            if(switch == 0):
                head.appendleft(c)
            else:
                tail.append(c)
        else:
            # put tail
            if(switch == 0):
                tail.append(c)
            else:
                head.appendleft(c)

reversed(head)
if(count_rev % 2 == 0):
    ans = list(head) + list(S) + list(tail)
else:
    s = list(S)
    s.reverse()
    ans = list(reversed(tail)) + s + list(reversed(head))

print(''.join(ans))

Submission status: Accepted

Solution code:
s=input()
s1=""
s2=""
count_1=0
l=[]
num =int(input())
 
 
for x in range(num):
    i=input().rstrip().split()
    if i[0]=="1":
        count_1+=1
        
    elif i[1]=="1" and count_1%2==0:
        s1=i[2]+s1
   
    elif i[1]=="1" and count_1%2==1:
        s2=s2+i[2]
 
    elif i[1]=="2" and count_1%2==0:
        s2=s2+i[2]
 
    elif i[1]=="2" and count_1%2==1:
        s1=i[2]+s1
s=s1+s+s2
 
if count_1%2==1:
    s=s[::-1]
print(s)

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
re = False
front = []
back = []

for i in range(Q):
    t = input()
    
    if len(t) == 1:
        re = not re
        
    else:
        q, f, c = t.split()
        if (re == True and int(f) == 2) or (re == False and int(f) == 1):
            front.append(c)
        elif (re == True and int(f) == 1) or (re == False and int(f) == 2):
            back.append(c)

if re == False:
    front.reverse()
    F = "".join(front)
    B = "".join(back)
    print(F + S + B)
else:
    back.reverse()
    S = S[::-1]
    F = "".join(front)
    B = "".join(back)
    print(B + S + F)

Submission status: Accepted

Solution code:
from collections import deque

s = input()
t = s[::-1]
ss = deque(s)
tt = deque(t)
isS = True
n = int(input())
query = []

# print(q1, q2)

for i in range(n):
    query.append(list(input().split()))

# print(query)

for i in range(n):
    # Reverse
    if query[i][0] == '1':
        # s = s[::-1]
        isS = not isS
    # Add
    else:
        # To Head
        if query[i][1] == '1':
            if isS:
                ss.appendleft(query[i][2])
                tt.append(query[i][2])
            else:
                ss.append(query[i][2])
                tt.appendleft(query[i][2])
        # To Tail
        else:
            if isS:
                ss.append(query[i][2])
                tt.appendleft(query[i][2])
            else:
                ss.appendleft(query[i][2])
                tt.append(query[i][2])

if isS:
    temp = list(ss)
    ans = ''.join(temp)
    print(ans)
else:
    temp = list(tt)
    ans = ''.join(temp)
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

reverse_status = False

for i in range(q):
  query = list(map(format, input().split()))
  if int(query[0]) == 1:
    if reverse_status:
      reverse_status = False
    else:
      reverse_status = True
  else:
    if int(query[1]) == 1:
      if reverse_status:
        s.append(query[2])
      else:
        s.appendleft(query[2])
    else:
      if reverse_status:
        s.appendleft(query[2])
      else:
        s.append(query[2])

if reverse_status:
  s.reverse()
print(''.join(s))

Submission status: Accepted

Solution code:
import collections
S = input()
Q = int(input())

query_list = [input().split() for _ in range(Q)]

T_cnt_list = collections.deque([0])
left = ''
right = ''

for i, query in enumerate(query_list):
    if query[0] == '1':
        T_cnt_list.append(1+T_cnt_list[-1])

    else:
        T_cnt_list.append(T_cnt_list[-1])

        if query[1] == '1' and T_cnt_list[i+1]%2 == 0:
            left = query[2] + left

        elif query[1] == '1' and T_cnt_list[i+1]%2 == 1:
            right = right + query[2]

        elif query[1] == '2' and T_cnt_list[i+1]%2 == 0:
            right = right + query[2]

        elif query[1] == '2' and T_cnt_list[i+1]%2 == 1:
            left = query[2] + left

if T_cnt_list[-1]%2 == 0:
    print(left + S + right)
else:
    print(right[::-1] + S[::-1] + left[::-1])

Submission status: Accepted

Solution code:
I = input
s = I()
q = int(I())
a = [], []
i = 0
for _ in range(q):
  x = I()
  if x[0] == '1':
    i ^= 1
  else:
    f = int(x[2]) - 1
    a[i ^ f].append(x[4])
r = ''.join(reversed(a[0])) + s + ''.join(a[1])
print(r[::-1] if i else r)

Submission status: Accepted

Solution code:
s = input()
q = int(input())
rev = 0
mae = []
usiro = []

for i in range(q):
    a = input()
    
    if a[0] == '1':
        rev += 1
    else:
        if (int(a[2]) + rev) % 2 == 1:
            mae.append(a[4])
        else:
            usiro.append(a[4])
            
mae = mae[::-1]
mae2 = "".join(mae)
usiro2 = "".join(usiro)
if rev%2 == 0:
    print(mae2 + s + usiro2)
else:
    ans = mae2 + s + usiro2
    print(ans[::-1])

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
import sys
from collections import deque
d=deque()
for _ in S:
  d.append(_)
flag=False

for _ in range(Q):
  s = list(sys.stdin.readline())
  if s[0]=="1":
    if flag:
      flag=False
    else:
      flag=True
  else:
    if s[2]=="1":
      if flag:
        d.append(s[4])
      else:
        d.appendleft(s[4])
    else:
      if flag:
        d.appendleft(s[4])
      else:
        d.append(s[4])
      
if flag:
  d.reverse()
  
print("".join(d))

Submission status: Accepted

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

reverse = 0
sento = ''
matsubi = ''

for i in range(q):
    inp = input()
    if len(inp) <= 1:
        reverse += 1
    else:
        dmy, f, c = inp.split()
        f = int(f)
        if reverse & 1:
            if f == 1:
                matsubi = matsubi + c
            else:
                sento = c + sento
        else:
            if f == 1:
                sento = c + sento
            else:
                matsubi = matsubi + c

s = sento + s + matsubi

if reverse & 1:
    print(s[::-1])
else:
    print(s)

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
turn = 0
head = ""
tail = ""
for i in range(Q):
  s = input().split()
  if s[0] == "1": # 反転
    turn += 1
  elif s[0] == "2": # 足す
    if (s[1] == "1" and turn % 2 == 0) or (s[1] == "2" and turn % 2 == 1):
      head = s[2] + head
    elif (s[1] == "2" and turn % 2 == 0) or (s[1] == "1" and turn % 2 == 1):
      tail = tail + s[2]
if turn % 2 == 0:
  print(head + S + tail)
else:
  print((head + S + tail)[::-1])

Submission status: Accepted

Solution code:
from collections import deque
s = deque(input())
qn = int(input())
q = []
rev = False

for i in range(qn):
    qi = input().split()
    if qi[0] == "1":
        rev = not rev
    else:
        if rev:
            if qi[1] == "1":
                qi[1] = "2"
            else:
                qi[1] = "1"
        q.append((2, int(qi[1]), qi[2]))
for i in range(len(q)):
    if q[i][0] == 2:
        if q[i][1] == 1:
            s.appendleft(q[i][2])
        else:
            s.append(q[i][2])
if rev:
    s = list(s)[::-1]
print("".join(s))

Submission status: Accepted

Solution code:
from collections import deque
d=deque()
S=list(input())
Q=int(input())
query=[list(map(str,input().split())) for _ in range(Q)]
flag=0  #反転なし
#print(query)
s=S
s2=""
d.extend(S)
#print(d)
for i in range(Q):
    #print(i,len(d))
    if (len(query[i])==1):
        if len(d)>1:
            flag=(flag+1)%2 #反転フラグをひっくり返す
    else:
        if flag==0:
            if query[i][1]=="1":
                d.appendleft(query[i][2])
            else:
                d.append(query[i][2])
        else:
            if query[i][1]=="2":
                d.appendleft(query[i][2])
            else:
                d.append(query[i][2])
    #print(d)
if flag==0:
    print("".join(list(d)))
else:
    d.reverse()
    print("".join(list(d)))

Submission status: Accepted

Solution code:
s = input("")
Q = int(input())
c = 0
before = []
after = []
for i in range(Q):
    t = input()
    if len(t) == 1:
        c += 1
    elif t[2] == "1":
        if c%2 == 0:
            before.append(t[4])
        else:
            after.append(t[4])
    else:
        if c%2 == 0:
            after.append(t[4])
        else:
            before.append(t[4])

if c%2 == 0:
    print("".join(before[::-1]),end="")
    print(s,end="")
    print("".join(after),end="")
else:
    print("".join(after[::-1]),end="")
    print(s[::-1],end="")
    print("".join(before),end="")

Submission status: Accepted

Solution code:
s = input()
q = int(input())
v = 0
fs = ''
rs = ''

for i in range(q):
    t = input().split()
    if t[0] == '1':
        v = v + 1
    elif t[0] == '2':
        if (t[1] == '1') and (v % 2 == 0):
            fs = t[2]+fs
        elif (t[1] == '1') and (v % 2 == 1):
            rs = rs + t[2]
        elif (t[1] == '2') and (v % 2 == 0):
            rs = rs + t[2]
        elif (t[1] == '2') and (v % 2 == 1):
            fs = t[2]+fs

if v % 2 == 0:
    s = fs + s + rs
else:
    s = fs + s + rs
    s = s[::-1]        
            
print (s)

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
q=[list(input().split()) for i in range(Q)]

top=[]
bot=[]
cnt=0
for i in range(Q):
    if q[i][0]=='1':
        cnt+=1
    if q[i][0]=='2':
        if cnt%2==0:
            if q[i][1]=='1':
                top+=q[i][2]
            if q[i][1]=='2':
                bot+=q[i][2]
        else:
            if q[i][1]=='1':
                bot+=q[i][2]
            if q[i][1]=='2':
                top+=q[i][2]

if cnt%2==1:
    ans=[S[::-1]]
    bot=bot[::-1]
    print(''.join(bot+ans+top))
else:
    ans=[S]
    top=top[::-1]
    print(''.join(top+ans+bot))

Submission status: Accepted

Solution code:
S=str(input())
Q=int(input())
count=0
M=''
U=''
for i in range(Q):
	a=list(map(str,input().split()))
	if a[0]=="1":
		count+=1
	elif a[0]=="2":
		if count%2==0:
			if a[1]=="1":
				M=a[2]+M
			elif a[1]=="2":
				U=U+a[2]
		elif count%2==1:
			if a[1]=="1":
				U=U+a[2][::-1]
			elif a[1]=="2":
				M=a[2][::-1]+M
S=M+S+U
if count%2==1:
	print(S[::-1])
else:
	print(S)

Submission status: Accepted

Solution code:
S = input()
S_h = ''
S_t = ''
Q = int(input())

def add_car(S_h,S_t,s,is_left,is_rev):
    if is_rev:
        is_left = not(is_left)
    if is_left:
        S_h = ''.join([S_h,s])
    else:
        S_t = ''.join([S_t,s])
    return S_h,S_t

is_rev = False
for q in range(Q):
    x = input().split(' ')
    if len(x) == 1:
        is_rev = not is_rev
    else:
        S_h,S_t = add_car(S_h,S_t,x[2],x[1]=='1',is_rev)

if is_rev:
    S_t = ''.join(list(reversed(S_t)))
    S = ''.join(list(reversed(S)))
    print(''.join([S_t,S,S_h]))
else:
    S_h = ''.join(list(reversed(S_h)))
    print(''.join([S_h,S,S_t]))

Submission status: Accepted

Solution code:
from collections import deque
def main():
  s=deque(list(input()))
  q=int(input())
  ok=1
  for i in range(q):
    query=list(input().split())
    if query[0]=='1':
      ok=(ok+1)%2
    else:
      f,c=query[1],query[2]
      if ok:
        if f=='1':
          s.appendleft(c)
        else:
          s.append(c)
      else:
        if f=='1':
          s.append(c)
        else:
          s.appendleft(c)
  s=list(s)
  if ok:
    print(''.join(s))
  else:
    print(''.join(s[::-1]))
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
from collections import deque

s = input()
q = int(input())
Q = [input() for _ in range(q)]

s = deque(list(s))
insert = s.appendleft
append = s.append
flag = True

for query in Q:
    if query[0] == '1':
        flag = not flag
    else:
        if (query[2] == '1' and flag) or (query[2] == '2' and not flag):
            insert(query[4])
        else:
            append(query[4])

if not flag:
    s.reverse()

print(*s, sep='')

Submission status: Accepted

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

sl = ['']*(q*2+2)
sl[q] = s
m = q-1
u = q+1
rev = False
for _ in range(q):
    query = input().split()

    if query[0] == '1' and not(rev):
        rev = True
    elif query[0] == '1' and rev:
        rev = False

    elif query[0] == '2' and query[1] == '1' and not(rev):
        sl[m] = query[2]
        m -= 1

    elif query[0] == '2' and query[1] == '1' and rev:
        sl[u] = query[2]
        u += 1

    elif query[0] == '2' and query[1] == '2' and not(rev):
        sl[u] = query[2]
        u += 1

    elif query[0] == '2' and query[1] == '2' and rev:
        sl[m] = query[2]
        m -= 1

if rev:
    sl[q] = s[::-1]
    sl.reverse()
    print(''.join(sl))
else:
    print(''.join(sl))

Submission status: Accepted

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

flag=0
forward=""
back=""
for i in range(Q):
    #query[i]=input()
    b=input()

    if(len(b)==1):
        #S=S[::-1]
        flag+=1
    else:
        a=b.split(" ")
        if(flag==0):
            if(a[1]=="1"):
                #S=a[2]+S
                forward=a[2]+forward
            else:
                #S+=a[2]
                back=back+a[2]
        else:
            if(a[1]=="1"):
                #S=a[2]+S
                back=back+a[2]
            else:
                #S+=a[2]
                forward=a[2]+forward
                
    flag=flag%2

S=forward+S+back
if(flag==1):
    S=S[::-1]
print(S)

Submission status: Accepted

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

front = ""
end = ""
f = 0
for i in range(Q):
    query = input().split()

    if query[0] == "1":
        if f == 0:
            f = 1
        else:
            f = 0
    else:
        if f == 0:
            if query[1] == "1":
                front = query[2] + front
            else:
                end = end + query[2]
        else:
            if query[1] == "2":
                front = query[2] + front
            else:
                end = end + query[2]

S = front + S + end
if f == 1:
    S = S[::-1]
print(S)