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: Wrong Answer

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():
	S = input()
	S = S[:-1]
	Q = inputInt()

	save = []

	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:
					S = inpt[2] + S
				else:
					S = S + inpt[2]
			else:
				if flg == True:
					S = S + inpt[2]
				else:
					S = inpt[2] + S

		if len(S) > 30000:
			save.append(S[1:-1])
			#print(save)
			S = S[0] + S[-1]
			#print(S)

	if flg == True:
		if len(save) > 0:
			tmp = "".join(save)
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		else:
			print(S)
	else:
		if len(save) > 0:
			print(save)
			print(S)
			S = S[::-1]
			tmp = "".join(save)
			tmp = tmp[::-1]
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		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: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(S, Q, Qvery):
    fw = True
    ret = []
    ret.append(S)
    for qvery in Qvery:
        if qvery[0] == 1:
            # fw = not fw
            if fw:
                fw = False
            else:
                fw = True
        elif qvery[0] == 2:
            if qvery[1] == 1 and fw or qvery[1] == 2 and not fw:  # 先頭に追加
                ret.insert(0, qvery[2])
                # S = qvery[2] + S
            else:  # 末尾に追加
                ret.append(qvery[2])
                # S = S + qvery[2]
        else:
            print("Parse error")

    if fw:
        print(''.join(ret))
    else:
        rev_ret = ret[::-1]
        print(''.join(rev_ret))


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = str(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    Qvery = []
    for i in range(Q):
        T = int(next(tokens))
        if T == 1:
            Qvery.append([1])
        elif T == 2:
            Qvery.append([2, int(next(tokens)), str(next(tokens))])
    solve(S, Q, Qvery)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
str = input()
N = int(input())
flag = False
for i in range(N):
    q = list(input().split())
    if (q[0] == '1'):
        if flag:
            flag = True
            continue
        str = str[::-1]
        flag = True
    else:
        if (q[1] == '1'):
            str = q[2]+str
        else:
            str = str + q[2]
        flag = False
print(str)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

queue = deque()
queue.append(s)


is_reverse = False

for _ in range(q):
    tfc = input()
    if tfc[0] == '1':
        is_reverse = not is_reverse
        continue
    else:
        if is_reverse == False and tfc[2] == '1':
            queue.appendleft(tfc[4])
        elif is_reverse == False and tfc[2] == '2':
            queue.append(tfc[4])
        elif is_reverse == True and tfc[2] == '1':
            queue.append(tfc[4])
        elif is_reverse == True and tfc[2] == '2':
            queue.appendleft(tfc[4])

if is_reverse:
    queue.reverse()
    ans = queue
    print(*ans, sep='')
else:
    ans = queue
    print(*ans, sep='')

Submission status: Wrong Answer

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

num_turn = 0

front = []
end = []

for i in range(Q):
    query = input()
    if query == '1':
        num_turn += 1
    else:
        _, f, c = query.split()
        f = int(f)
        if f == 1:
            if num_turn%2==0:
                front.append(c)
            else:
                end.append(c)
        else:
            if num_turn%2==0:
                end.append(c)
            else:
                front.append(c)

S = list(S)
if num_turn%2==1:
    ans = end[::-1] + S[::-1] + front
else:
    ans = front + S + end[::-1]
print(''.join(ans))

Submission status: Wrong Answer

Solution code:
s = list(input())
len_queries = int(input())
queries = [input().split() for _ in range(len_queries)]

is_forward = True
for query in queries:
    if "1" == query[0]:
        is_forward = not is_forward
    else:
        if is_forward:
            insert_index = 0 if "1" == query[1] else -1
            s.insert(insert_index, query[2])
        else:
            insert_index = -1 if "1" == query[1] else 0
            s.insert(insert_index, query[2])
if not is_forward:
    s.reverse()
print("".join(s))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from string import ascii_uppercase
import sys, bisect, math, heapq

stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

S = read_str()
Q = read_int()[0]
Query = [list(read_str().split()) for _ in range(Q)]

def solve():
    res = S
    res_r = S[::-1]
    reverse = False
    for q in Query:
        if q[0] == '1':
            reverse = not reverse
        else:
            if reverse:
                if q[1] == '1':
                    res += q[2]
                else:
                    res_r += q[2]
            else:
                if q[1] == '1':
                    res_r += q[2]
                else:
                    res += q[2]
        # print(res, res_r, reverse)
    ans = ''
    if reverse:
        ans = res + res_r[1:]
    else:
        ans = res_r[::-1] + res[1:]
    return ans

if __name__ == "__main__":
    print(solve())

Submission status: Wrong Answer

Solution code:
from collections import deque

s = deque()
s.append(input())
q = int(input())
flg = False
for i in range(q):
    query = input()
    if query[0] == '1': flg = not flg
    else:
        t,f,c = query.split()
        if flg:
            s.appendleft(c) if f=='2' else s.append(c)
        else:
            s.appendleft(c) if f=='1' else s.append(c)
if flg: s = reversed(s)
print(''.join(s))

Submission status: Wrong Answer

Solution code:
import itertools
import sys
import math
import numpy as np
from collections import deque
from itertools import combinations
from functools import reduce
from functools import lru_cache
sys.setrecursionlimit(10**9)

def main():
    S = input()
    Q = int(input())

    str = [S[0]] if len(S) == 1 else list(S.split())
    def insert(s,type):
        if type == 1:
            str.insert(0,s)
        else:
            str.append(s)


    non_reverse = True
    for _ in range(Q):
        inp = input()
        if inp == "1":
            non_reverse = not non_reverse
        else:
            _,F,C = inp.split()
            F = int(F)
            if non_reverse:
                insert(C,F)
            else:
                insert(C,1 if F == 2 else 2)

    if non_reverse:
        print("".join(str))
    else:
        print("".join(reversed(str)))



if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
S=input()
Q=int(input())
q=[list(input().split()) for i in range(Q)]
ans=[S]
for i in range(Q):
    if q[i][0]=='1':
        ans=ans[::-1]
    if q[i][0]=='2':
        if q[i][1]=='1':
            ans[0:0]=q[i][2]
        if q[i][1]=='2':
            ans.append(q[i][2])
print(''.join(ans))

Submission status: Wrong Answer

Solution code:
def main(s,x,q):
    res = s
    rev = 1 #-1なら反転中
    for op in q:
        if int(op[0]) == 1:
            rev = rev * -1
        elif int(op[0]) == 2:
            if int(op[1])*rev == 1 or int(op[1])*rev != 2:
                res = op[2] + res
            else:
                res = res + op[2]
    if rev == -1:
        res = res[::-1]
    return res

s = input()
x = int(input())
q = [input().split() for _ in range(x)]
print(main(s,x,q))

Submission status: Wrong Answer

Solution code:
init = input()
num = int(input())

_strings = [''] * num
_strings[0] = init

i = 0
while i < num:
    query = input().split()
    type = int(query[0])

    if type == 1:
        _strings.reverse()
    else:
        mode = int(query[1])
        if mode == 1:
            _strings.insert(0, str(query[2]))
        else:
            _strings.append(str(query[2]))

    i += 1

print(''.join(_strings))

Submission status: Wrong Answer

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():
	S = input()
	S = S[:-1]
	Q = inputInt()

	save = []

	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:
					S = inpt[2] + S
				else:
					S = S + inpt[2]
			else:
				if flg == True:
					S = S + inpt[2]
				else:
					S = inpt[2] + S

		if len(S) > 10000:
			save.append(S[1:-1])
			#print(save)
			S = S[0] + S[-1]
			#print(S)

	if flg == True:
		if len(save) > 0:
			tmp = "".join(save)
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		else:
			print(S)
	else:
		if len(save) > 0:
			print(save)
			print(S)
			S = S[::-1]
			tmp = "".join(save)
			tmp = tmp[::-1]
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		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: Wrong Answer

Solution code:
s = list(input())
q = int(input())
hanten = 0
for i in range(q):
  nyuuryoku = input().split()
  n = nyuuryoku[0]
  if len(nyuuryoku) == 1:
    hanten += 1
    continue
  else:
    f = int(nyuuryoku[1])
    c = nyuuryoku[2]
    if hanten%2 == 0:
      if f ==1:
        s.insert(0,c)
      else:
        s.insert(-1,c)
    else:
      if f == 1:
        s.insert(-1,c)
      else:
        s.insert(0,c)
if hanten%2 == 1:
  s.reverse()
ans = "".join(s)
print(ans)

Submission status: Wrong Answer

Solution code:
moji=input()
times=int(input())

sento=[]
sippo=[]
plus=[sento,sippo]
dictionary={"sento":0,"sippo":1}

hantenkaisuu=0

for i in range(times):
    command=input().split()
    
    #反転の命令
    if command[0]=="1":
        hantenkaisuu+=1
        dictionary["sento"]=1
        dictionary["sippo"]=0
        
    #追加の命令
    else:
        if command[1]=="1":
            plus[dictionary["sento"]].append(command[2])
        else:
            plus[dictionary["sippo"]].append(command[2])
            
            
    
    
if hantenkaisuu%2==0:
    sento=sento[::-1]
    sento="".join(sento)
    sippo="".join(sippo)
    print(sento+moji+sippo)
else:
    sippo=sippo[::-1]
    sento="".join(sento)
    sippo="".join(sippo)
    moji=moji[::-1]
    print(sippo+moji+sento)

Submission status: Wrong Answer

Solution code:
import sys

S = input().split()
Q = int(input())
QUERY = sys.stdin.readlines()

state = 0
q1 = []
q2 = []
for i in range(Q):
    query = QUERY[i]
    if query[0] == '1':
        state ^= 1
    else:
        _, F, C = query.split()
        if (state + int(F)) % 2:
            q1.append(C)
        else:
            q2.append(C)

ans = ''
if state == 0:
    print(*reversed(q1), end='', sep='')
    print(*S, end='', sep='')
    print(*q2, sep='')
else:
    print(*reversed(q2), end='', sep='')
    print(*reversed(S), end='', sep='')
    print(*q1, sep='')

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

S=input()[:-1]
print(S)
Q=int(input()[:-1])
print(Q)
f=0

for _ in range(Q):
    q=input().split()
    if int(q[0])==1:
        f = (f+1)%2
    if int(q[0])==2:
        if int(q[1])==1:
            if f==0:
                S=q[2]+S
            else:
                S=S+q[2]
        else:
            if f==0:
                S=S+q[2]
            else:
                S=q[2]+S
if f==0:
    print(S)
else:
    print(S[::-1])

Submission status: Wrong Answer

Solution code:
s=input().split()
a=int(input())
for i in range(a):
  n=input().split()
  if(n[0]=="1"):
    s =list(reversed(s))
  elif(n[0]=="2" and n[1]=="1"):
      s.insert(0,n[2])
  else:
      s.append(n[2])
s=''.join(s)
print(s)

Submission status: Wrong Answer

Solution code:
def do(s, query, isReverse):
    if(query[0] == "1"):
        return s, isReverse * -1
    else:
        if(query[1] == "1"):
            if(isReverse == 1):
                return "".join([s, query[2]]), isReverse
            else:
                return "".join([query[2], s]), isReverse
        else:
            if(isReverse == 1):
                return "".join([query[2], s]), isReverse
            else:
                return "".join([s, query[2]]), isReverse

s = input()
q = int(input())
isReverse = -1
for i in range(q):
    query = input().split()
    #s, isReverse = do(s, query, isReverse)
if(isReverse == -1):
    print(s)
else:
    print(s[::-1])

Submission status: Wrong Answer

Solution code:
def resolve():
    S = input()
    Q = int(input())
    Q_list = []
    tmp_before = ""

    for i in range(Q):
        tmp = input()
        if tmp_before == '1' and tmp == '1':
            tmp_before = ""
            Q_list.pop(-1)
            break
        Q_list.append(tmp)
        tmp_before = tmp

    for q in Q_list:
        q_list = list(q.split())
        if q_list[0] == '1':
            S = S[::-1]
        else:
            F = q_list[1]
            C = q_list[2]
            if F == '1':
                S = C + S
            else:
                S = S + C

    print(S)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
s = list(input())
Q = int(input())
for i in range(Q):
    q = input().split()
    if int(q[0]) == 1:
        s[0], s[-1] = s[-1], s[0]
    else:
        if int(q[1]) == 1:
            s = list(q[2]) + s
        else:
            s.append(q[2])
print("".join(s))

Submission status: Wrong Answer

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

for i in range(Q):
    q = input().split()
    if int(q[0]) == 1:
        S = S[::-1]
    else:
        F = int(q[1])
        C = q[2]
        if F == 1:
            S.insert(0, C)
        else:
            S.append(C)

print("".join(S))

Submission status: Wrong Answer

Solution code:
S = input()
Q = int(input())
query = [S]
for _ in range(Q):
    Query = input().split()
    if len(Query) == 1:
        _h = query[0]
        _t = query[-1]
        query[0] = _t
        query[-1] = _h
    elif int(Query[1]) == 1:
        query.insert(0, Query[2])
    else:
        query.append(Query[2])
print(''.join(query))

Submission status: Wrong Answer

Solution code:
from collections import deque

S = deque(input())
Q = int(input())
query = [input().split() for _ in range(Q)]
r = 0
for q in query:
    if q[0] == '1':
        r += 1
    else:
        if r % 2:
            if q[1] == '1':
                S.appendleft(q[2])
            else:
                S.append(q[2])
        else:
            if q[1] == '1':
                S.append(q[2])
            else:
                S.appendleft(q[2])
if r % 2 == 0:
    S.reverse()
print(''.join(S))

Submission status: Wrong Answer

Solution code:
from collections import deque
d = deque()
d.append(input())
q = int(input())
for i in range(q):
  qu = input().split()
  if qu[0] == "1":
    d.reverse()
  else:
    if qu[1] == "1":
      d.appendleft(qu[2])
    else:
      d.append(qu[2])

print(''.join(list(d)))

Submission status: Wrong Answer

Solution code:
s = list(input())
q = int(input())
s0 = []
s1 = []
for _ in range(q):
    ql = list(input().split())
    if ql[0] == '1':
        s0[-1:], s1[-1:] = s1[-1:], s0[-1:]
    else:
        if ql[1] == '1':
            s0 += ql[2]
        else:
            s1 += ql[2]

ans = s0 + s + s1
print(*ans, sep='')

Submission status: Wrong Answer

Solution code:
from collections import deque

S = input()
Q = int(input())
ans = deque()
ans.append(S)
reverse = False

for _ in range(Q):
    query = input().split()
    if query[0] == "1":
        reverse = not reverse
    if query[0] == "2":
        F, C = query[1:]
        if (F == "1" and not reverse) or (F == "2" and reverse):
            ans.appendleft(C)
        else:
            ans.append(C)

if reverse:
    print("".join(reversed(ans)))
else:
    print("".join(ans))

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
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 LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	S = IS()
	Q = II()
	c = 0
	head=[]
	tail=[]
	for _  in range(Q):
		query = IS()
		if(len(query)==1):
			c = (c + 1)%2
		else:
			print(query)
			T,F,C = query.split()
			T = int(T)
			F = int(F)
			if F==1:
				if(c==0):
					head.append(C)
				else:
					tail.append(C)
			else:
				if(c==1):
					head.append(C)
				else:
					tail.append(C)
	if c == 0:
		head = ''.join(head[::-1])
		tail = ''.join(tail)
		ans = head+S+tail
	else:
		head = ''.join(head)
		tail = "".join(tail[::-1])
		ns = S[::-1]
		ans = tail+ns+head
	print(ans)




if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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():
	S = input()
	S = S[:-1]
	Q = inputInt()

	save = []

	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:
					S = inpt[2] + S
				else:
					S = S + inpt[2]
			else:
				if flg == True:
					S = S + inpt[2]
				else:
					S = inpt[2] + S

		if len(S) > 10:
			save.append(S[1:-1])
			#print(save)
			S = S[0] + S[-1]
			#print(S)

	if flg == True:
		if len(save) > 0:
			tmp = "".join(save)
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		else:
			print(S)
	else:
		if len(save) > 0:
			print(save)
			print(S)
			S = S[::-1]
			tmp = "".join(save)
			tmp = tmp[::-1]
			ind = len(S) // 2
			if len(S) % 2 != 0:
				ind += 1
			print(S[:ind] + tmp + S[ind:])
		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: Wrong Answer

Solution code:
s = []
s.append(input())
g = 0
q = int(input())
for i in range(q):
	d = input().split(" ")
	if d[0] == "1":
		if g == 0:
			g = 1
		else:
			g = 0
	if d[0] == "2":
		f = d[1]
		if g == 0:
			if f == "1":
				s.insert(0, d[2])
			else:
				s.append(d[2])
		else:
			if f == "1":
				s.append(d[2])
			else:
				s.insert(0, d[2])
if g == 1:
	s.reverse()
	ans = "".join(s)
	print(ans)
else:
	ans = "".join(s)
	print(ans)

Submission status: Wrong Answer

Solution code:
s=input()
t=int(input())
left=""
right=""
rev=0
for i in range(t):
    arr=input().split()
    if len(arr)==1:
        rev+=1 
    else:
        if arr[1]=="1":
            if rev&1==0:
                left=arr[2]+left
               
            else:
                right=arr[2]+right
               
        else:
            if rev&1==1:
                left=arr[2]+left 
               
            else:
                right+=arr[2]
if rev&1:
    ans=right+s+left[::-1] 
else:
    ans=left+s+right
print(ans)