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=deque(list(input()))
q=int(input())
count=0
for i in range(q):
    query=input()
    if query=="1":
        count+=1
    elif query[2]=="1":
        if count%2==0:
            s.appendleft(query[-1])
        else:
            s.append(query[-1])
    else:
        if count%2==0:
            s.append(query[-1])
        else:
            s.appendleft(query[-1])
if count%2==1:
    s.reverse()
print(*s,sep="")

Submission status: Accepted

Solution code:
from collections import deque


Q=deque(list(input()))

q=int(input())

cnt=0

for i in range(q):
  x=input()
  if x[0]=='1':
    cnt+=1
    cnt%=2
    
  elif x[0]=='2':
    if x[2]=='1':
        if cnt%2==0:
            Q.appendleft(x[4])
        else:
            Q.append(x[4])

    else:
        if cnt%2==0:
            Q.append(x[4])
        else:
            Q.appendleft(x[4])
      
if cnt%2==1:
  Q.reverse()


print(''.join(Q))

Submission status: Accepted

Solution code:
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


S = LS2()
r = 0
left,right = [],[]

Q = I()
for i in range(Q):
    A = LS()
    if A[0] == '1':
        r = 1-r
    else:
        f,c = A[1],A[2]
        if (r == 0 and f == '1') or (r == 1 and f == '2'):
            left.append(c)
        else:
            right.append(c)

if r == 0:
    left.reverse()
    print(''.join(left+S+right))
else:
    S.reverse()
    right.reverse()
    print(''.join(right+S+left))

Submission status: Accepted

Solution code:
import sys
from collections import deque


def LS():
    return list(input().split())


S = deque(input())
Q = int(input())
rev = 0
for i in range(Q):
    A = LS()
    if A[0] == "1":
        rev += 1
        rev %= 2
    else:
        if A[1] == "1":
            if rev == 0:
                S.appendleft(A[2])
            else:
                S.append(A[2])
        else:
            if rev == 0:
                S.append(A[2])
            else:
                S.appendleft(A[2])
if rev == 0:
    print(''.join(S))
else:
    S.reverse()
    print(''.join(S))

Submission status: Accepted

Solution code:
from collections import deque
S = input()
ds = deque(S)
Q = int(input())
query = []
for i in range(Q):
  tq = list(input().split())
  if (len(tq) == 1):
    query.append(1)
  if (len(tq) == 3):
    query.append([int(tq[1]),tq[2]])
eo = 1
for q in query:
  if q == 1:
    eo = eo*(-1)
  else:
    eoq = eo*q[0]
    if eoq == 1 or eoq == -2:
      ds.extendleft(q[1])
    else:
      ds.extend(q[1])
jds = "".join(ds)
if eo == -1:
  jds = jds[::-1]
print(jds)

Submission status: Accepted

Solution code:
S = input()
T = ""
B = ""
f = 1
for _ in range(int(input())):
    L = list(input().split())
    if L[0] == "1":
        f *= -1
    else:
        if f == 1:
            if L[1] == "1":
                T += L[2]
            else:
                B += L[2]
        else:
            if L[1] == "1":
                B += L[2]
            else:
                T += L[2]

if f == 1:
    print(T[::-1]+S+B)
else:
    print(B[::-1]+S[::-1]+T)

Submission status: Accepted

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode

INF = float("inf")

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

s = S()
q = I()
# Q = LS(q)

# print(Q)

# a = 'A'
flag = True
r = []
l = []
for i in range(q):
    d = input().split()
    if len(d)==1:
        flag = not flag
    elif d[1]=='1':
        c = d[2]
        if flag:
            l.append(c)
        else:
            r.append(c)
    elif d[1]=='2':
        c = d[2]
        if flag:
            r.append(c)
        else:
            l.append(c)
# print(l)
# print(r)
l = "".join(l[::-1])
r = "".join(r)
ans = l+s+r
if flag:
    print(ans)
else:
    print(ans[::-1])

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
  return int(readline())
s = input()
q = I()
straight = True
ans = deque(s)
for i in range(q):
    A = input().split()
    if A[0] == '1':
        straight = not straight
    else:
        if straight:
            if A[1] == '1':
                ans.appendleft(A[2])
            else:
                ans.append(A[2])
        else:
            if A[1] == '1':
                ans.append(A[2])
            else:
                ans.appendleft(A[2])
if straight:
    print(*ans,sep='')
else:
    print(*reversed(ans),sep='')

Submission status: Accepted

Solution code:
from collections import deque
import sys
read = sys.stdin.readline

s = deque(read().rstrip())
q = int(read())

rev = 0
for _ in range(q):
    a = tuple(read().split())
    if a[0] == '1':
        rev ^= 1
    else:
        dir = rev ^ int(a[1]) - 1
        if dir == 0:
            s.appendleft(a[2])
        else:
            s.append(a[2])

if rev:
    print(''.join(s)[::-1])
else:
    print(''.join(s))

Submission status: Accepted

Solution code:
S = input().strip()
Q = int(input())
ind = 1
x = []
y = []
for i in range(Q):
    q = list(input().split())
    if len(q)==1:
        ind = ind*(-1)
    else:
        if q[1]=="1":
            if ind>0:
                x.append(q[2])
            else:
                y.append(q[2])
        else:
            if ind>0:
                y.append(q[2])
            else:
                x.append(q[2])
if ind>0:
    x = x[::-1]
    S = "".join(x)+S+"".join(y)
else:
    S = S[::-1]
    y = y[::-1]
    S = "".join(y)+S+"".join(x)
print(S)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  #空白あり
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし


S = LS2()
r = 0
left,right = [],[]

Q = I()
for i in range(Q):
    A = LS()
    if A[0] == '1':
        r = 1-r
    else:
        f,c = A[1],A[2]
        if (r == 0 and f == '1') or (r == 1 and f == '2'):
            left.append(c)
        else:
            right.append(c)

if r == 0:
    left.reverse()
    print(''.join(left+S+right))
else:
    S.reverse()
    right.reverse()
    print(''.join(right+S+left))

Submission status: Accepted

Solution code:
import sys
from collections import deque


def input():
    return sys.stdin.readline().strip()


S = input()
Q = int(input())
q = deque(S)
flipped = False
for _ in range(Q):
    q_t, *q_d = input().split()
    if q_t == "1":
        flipped = not flipped
    else:
        F, C = q_d
        if (not flipped and F == "2") or (flipped and F == "1"):
            q.append(C)
        else:
            q.appendleft(C)

ans = list(q)
if flipped:
    print("".join(ans[::-1]))
else:
    print("".join(ans))

Submission status: Accepted

Solution code:
s = list(str(input()))
q = int(input())
flag = 1
from collections import deque
s = deque(s)
for i in range(q):
    query = list(map(str, input().split()))
    if len(query) == 1:
        flag = 1-flag
    else:
        t, f, c = query
        if f == '1':
            if flag:
                s.appendleft(c)
            else:
                s.append(c)
        else:
            if flag:
                s.append(c)
            else:
                s.appendleft(c)

s = list(s)
if not flag:
    s.reverse()
print(''.join(s))

Submission status: Accepted

Solution code:
from collections import deque
S = deque(input())
Q = int(input())
q = [input().split() for _ in range(Q)]
flag = True
for x in q:
    if x[0] == "1":
        if flag: flag = False
        else: flag = True
    else:
        if x[1] == "1":
            if flag: S.appendleft(x[2])
            else: S.append(x[2])
        else:
            if flag: S.append(x[2])
            else: S.appendleft(x[2])
s = list(S)
if not flag: s = s[::-1]
print("".join(s))

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

from collections import deque
def main():
    S_ = S()
    S_que = deque(S_)
    Q = I()
    cnt = 0
    for i in range(Q):
        q = LS()
        if int(q[0]) == 1:
            cnt += 1
        elif int(q[0]) == 2:
            if int(q[1]) == 1:
                if cnt % 2 == 0:
                    S_que.appendleft(q[2])
                else:
                    S_que.append(q[2])
            else:
                if cnt % 2 == 1:
                    S_que.appendleft(q[2])
                else:
                    S_que.append(q[2])
    if cnt % 2 == 1:
        S_que.reverse()
    print(''.join(map(str, S_que)))

if __name__ == "__main__":
    main()

Submission status: Accepted

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

input = sys.stdin.readline


def ST():
    return input().rstrip()


def I():
    return int(input())


def MI():
    return map(int, input().split())


def LI():
    return list(MI())


S = ST()
Q = I()

switch = True
prefix = ""
suffix = ""
for _ in range(Q):
    query = list(input().split())
    if query[0] == "1":
        if switch:
            switch = False
        else:
            switch = True
    else:
        if switch:
            if query[1] == "1":
                prefix = query[2] + prefix
            else:
                suffix = suffix + query[2]
        else:
            if query[1] == "1":
                suffix = suffix + query[2]
            else:
                prefix = query[2] + prefix

ans = prefix + S + suffix
if switch:
    print(ans)
else:
    print(ans[::-1])

Submission status: Accepted

Solution code:
s=input()
q=int(input())
quary=[]
for i in range(q):
    temp=list(input().split())
    quary.append(temp)
switch=False
first=''
last=''
for i in range(q):
    if quary[i][0]=='1':
        if switch:
            switch=False
        else:
            switch=True

    else:
        if quary[i][1]=='1':
            if switch:
                last+=quary[i][2]
            else:
                first+=quary[i][2]
        else:
            if switch:
                first+=quary[i][2]
            else:
                last+=quary[i][2]
s=first[::-1]+s+last
if switch:
    print(s[::-1])
else:
    print(s)

Submission status: Accepted

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

# 0の時は普通、1の時は反転状態
Reverse_Flag = 0  

for _ in range(Q):
    string = (input())
    Query = string.replace(' ', '')
    Query = list(Query)

    if Query[0] == "1":
        if Reverse_Flag == 0:
            Reverse_Flag = 1
        else:
            Reverse_Flag = 0
    
    elif  Query[1] == "1":
        if Reverse_Flag == 0:
            S.appendleft(Query[2])
        else:
            S.append(Query[2])

    else:
        if Reverse_Flag == 0:
            S.append(Query[2])
        else:
            S.appendleft(Query[2])

if Reverse_Flag == 1:
    S = list(S)
    S = S[::-1]
    print("".join(S))
else:
    S = list(S)
    print("".join(S))

Submission status: Accepted

Solution code:
from collections import deque
s = deque(list(input()))
q = int(input())
flg = True
for _ in range(q):
    try:
        t,f,c = input().split()
        if flg:
            if f == "1":
                s.appendleft(c)
            else:
                s.append(c)
        else:
            if f == "1":
                s.append(c)
            else:
                s.appendleft(c)
    except ValueError:
        if flg:
            flg = False
        else:
            flg = True
if flg:
    print(''.join(s))
else:
    s = list(reversed(s))
    print(''.join(s))

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
Q=[input().split() for i in range(Q)]
Forward=[]
Backward=[]
count=0
for i in Q:
    if i[0]=='1':
        count+=1
    else:
        if (int(i[1])+count)%2==1:
            Forward.append(i[2])
        else:
            Backward.append(i[2])  
if count%2==0:
    ans = (''.join(Forward))[::-1]+S+(''.join(Backward))
else:
    ans = (''.join(Backward)[::-1]+S[::-1]+(''.join(Forward)))
print(ans)

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
q = []
for i in range(Q):
    a = input().split(" ")
    if len(a) == 1:
        q.append([int(a[0])])
    else:
        q.append([int(a[0]), int(a[1]), a[2]])

#print(S)
#print(q)

def switch(s):
    d = ""
    for i in range(len(s)):
        d += s[len(s) - i - 1]
    return d

H = ""
B = ""

direction = 1 #通常の向き　-1:反対方向

for t in range(len(q)):
    T = q[t]
    if T[0] == 1:
        direction *= -1
    else:
        F = T[1]
        C = T[2]
        if F == 1:
            if direction == 1:
                H += C
            else:
                B += C
        else:
            if direction == 1:
                B += C
            else:
                H += C

if direction == 1:
    print(switch(H) + S + B)
else:
    print(switch(B) + switch(S) + H)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: 	D_fix_3
# CreatedDate:  2020-08-30 13:22:07 +0900
# LastModified: 2020-08-30 13:41:03 +0900
#


import os
import sys
# import numpy as np
# import pandas as pd


def main():
    S = input()
    Q = int(input())
    appendix_1 = ''
    appendix_2 = ''
    reverse = 0
    for _ in range(Q):
        q = list(input().split())
        if q[0] == '1':
            reverse += 1
        else:
            if q[1] == '1' and reverse % 2 == 0:
                appendix_1 += q[2]
            elif q[1] == '1' and reverse % 2 == 1:
                appendix_2 += q[2]
            if q[1] == '2' and reverse % 2 == 0:
                appendix_2 += q[2]
            elif q[1] == '2' and reverse % 2 == 1:
                appendix_1 += q[2]

    if reverse % 2 == 0:
        print(appendix_1[::-1] + S + appendix_2)
    else:
        print(appendix_2[::-1] + S[::-1] + appendix_1)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque


inint = lambda: int(sys.stdin.readline())
inintm = lambda: map(int, sys.stdin.readline().split())
inintl = lambda: list(inintm())
instrm = lambda: map(str, sys.stdin.readline().split())
instrl = lambda: list(instrm())

s = input()
q = inint()

S = deque()
f = [0,1]

for i in range(len(s)):
    S.append(s[i])

for i in range(q):
    Q = instrl()
    if Q[0] == "1":
        f = f[::-1]
    else:
        if f[0] == 0:
            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 f[0] == 1:
    S.reverse()

print("".join(S))

Submission status: Accepted

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

f = 0
for i in range(q):
    t = input().split()
    if t[0] == "1":
        if f % 2 == 0:
            f = 1
        else:
            f = 0
    elif t[0] == "2":
        if t[1] == "1":
            if f == 1:
                usiro.append(t[2])
            else:
                mae.append(t[2])
        elif t[1] == "2":
            if f == 1:
                mae.append(t[2])
            else:
                usiro.append(t[2])

mae = mae[::-1]
ans = "".join(mae)+s+"".join(usiro)
if f:
    print(ans[::-1])
else:
    print(ans)

Submission status: Accepted

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

def main():
    S = input().replace('\n', '')
    Q = int(input())

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

Submission status: Accepted

Solution code:
from collections import deque
S = list(input())
Q = int(input())
reverse = 1

d = deque()
for i in S:
  d.append(i)


for i in range(Q):
  temp = input().split()
  if temp[0] == "1":
    reverse = -reverse
  else:
    if temp[1] == "1" :
      if reverse == 1:
        d.appendleft(temp[2])
      else:
        d.append(temp[2])
    else:
      if reverse == 1:
        d.append(temp[2])
      else:
        d.appendleft(temp[2])
      
      
length = len(d)
for _ in range(length):
  temp = 0
  if reverse == 1:
    temp = d.popleft()
  else:
    temp = d.pop()
  print(temp, end="")

Submission status: Accepted

Solution code:
from collections import deque

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

rl=1
fleft=deque()
fright=deque()

for i in qq:
  if i[0]=='1':
    rl*=-1
  else:
    if i[1]=='1':
      if rl==1:
        fleft.appendleft(i[2])
      else:
        fright.append(i[2])
    else:
      if rl==1:
        fright.append(i[2])
      else:
        fleft.appendleft(i[2])

fleft.reverse()

s.extendleft(fleft)
s.extend(fright)

if rl==-1:
  s.reverse()

print(''.join(s))

Submission status: Accepted

Solution code:
from collections import deque
import sys

input=sys.stdin.readline

S=input().rstrip()

string = deque([S[i] for i in range(len(S))])

reverse = False

for _ in range(int(input())):
    q = input().rstrip().split()

    if q[0] == "1":
        reverse = not reverse

    else:
        if q[1] == "1":
            if reverse:
                string.append(q[2])
            else:
                string.appendleft(q[2])

        else:
            if reverse:
                string.appendleft(q[2])
            else:
                string.append(q[2])

string = list(string)

if reverse:
    string = string[::-1]

print("".join(string))

Submission status: Accepted

Solution code:
from collections import deque
S = deque(input())
Q = int(input())
d = 0 # d=0:right, d=1:left
for i in range(Q):
  I = list(input().split())
  if I[0] == "1":
    d ^= 1
  else:
    if d + int(I[1]) == 2:
      S.append(I[2])
    else:
      S.appendleft(I[2])
if d == 1:
  S.reverse()
for s in S:
  print(s, end="")
print()

Submission status: Accepted

Solution code:
import sys
# sys.setrecursionlimit(100000)
from collections import deque


def input():
    return sys.stdin.readline().strip()


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    s = deque(list(input()))
    q = input_int()
    inverse = False
    for _ in range(q):
        data = input().split()
        if len(data) == 1:
            inverse = not inverse
        else:
            if (data[1] == "1" and not inverse) or (data[1] == "2" and inverse):
                s.appendleft(data[2])
            else:
                s.append(data[2])
    if inverse:
        print("".join(reversed(s)))
    else:
        print("".join(s))
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
p=0
u=0
l=""
r=""
for i in range(Q):
    q=list(input().split())
    if q[0]=="1":
        u+=1
    else:
        if q[1]=="1" and u%2==0 or q[1]=="2" and u%2==1:
            l=l+q[2]
        else:
            r=r+q[2]
if u%2==0:
    l=l[::-1]
    S=l+S+r
else:
    S=S[::-1]
    r=r[::-1]
    S=r+S+l
print(S)

Submission status: Accepted

Solution code:
S = list(input())
Q = int(input())
re = False
top = []
end = []
for i in range(Q):
    line = list(map(str,input().split()))
    if line[0] == '1':
        if re == True:
            re = False
        else:
            re = True
    else:
        if (re == False and line[1] == '1') or (re == True and line[1] == '2'):
            top.append(line[2])
        else:
            end.append(line[2])

if re == True:
    S.reverse()
    end.reverse()
    ans = end + S + top
else:
    top.reverse()
    ans = top + S + end
print(''.join(ans))

Submission status: Accepted

Solution code:
# import itertools
# import math
# import sys
# sys.setrecursionlimit(500*500)
# import numpy as np

# N = int(input())
S = input()
# n, *a = map(int, open(0))
# N, M = map(int, input().split())
# A = list(map(int, input().split()))
# B = list(map(int, input().split()))
# tree = [[] for _ in range(N + 1)]
# B_C = [list(map(int,input().split())) for _ in range(M)]
# S = input()

# B_C = sorted(B_C, reverse=True, key=lambda x:x[1])
# all_cases = list(itertools.permutations(P))
# a = list(itertools.combinations_with_replacement(range(1, M + 1), N))
# itertools.product((0,1), repeat=n)

# A = np.array(A)
# cum_A = np.cumsum(A)
# cum_A = np.insert(cum_A, 0, 0)

# def dfs(tree, s):
#     for l in tree[s]:
#         if depth[l[0]] == -1:
#             depth[l[0]] = depth[s] + l[1]
#             dfs(tree, l[0])
# dfs(tree, 1)

Q = int(input())
query = [list(input().split()) for _ in range(Q)]
direction = 1
S_front = ""
S_back = ""
for l in query:
    if l[0] == "1":
        direction *= -1
    else:
        if (l[1] == "1" and direction == 1) or (l[1] == "2" and direction == -1):
            S_front += l[2]
        else:
            S_back += l[2]

if direction == 1:
    print(S_front[::-1] + S + S_back)
else:
    print(S_back[::-1] + S[::-1] + S_front)

Submission status: Accepted

Solution code:
from collections import deque
S = input()
Q = int(input())
R = deque(S)
rev = 0

for i in range(Q):
    T = input().split()
    if T[0] == '1':
        rev += 1
    else:
        if T[1] == '1':
            if rev % 2 == 0:
                R.appendleft(T[2])
            else:
                R.append(T[2])
        else:
            if rev % 2 == 0:
                R.append(T[2])
            else:
                R.appendleft(T[2])
ans = ''.join(R)
if rev % 2 ==0:
    print(ans)
else:
    print(ans[::-1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
def main():
    import sys
    from collections import deque

    input = sys.stdin.readline

    S = input().rstrip()
    Q = int(input())

    S = deque(S)
    rev = 0
    for _ in [0] * Q:
        q = input().split()
        if q[0] == '1':
            rev += 1
        else:
            if q[1] == '1':
                S.append(q[2]) if rev % 2 else S.appendleft(q[2])
            else:
                S.appendleft(q[2]) if rev % 2 else S.append(q[2])
    ans = ''.join(S)
    print(ans[::-1] if rev % 2 else ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
from collections import deque
s=deque(input())
Q=int(input())
count=0
query=[]
for i in range(Q):
    arr=input().split()
    query.append(arr)

for i in range(Q):
    if query[i][0]=="1":
        count+=1
    else:
        if count%2==0:
            if query[i][1]=="1":
                s.appendleft(query[i][2])
            else:
                s.append(query[i][2])
        else:
            if query[i][1]=="1":
                s.append(query[i][2])
            else:
                s.appendleft(query[i][2])
if count%2==0:
    for i in range(len(s)):
        print(s[i],end="")
        
else:
    s.reverse()
    for i in range(len(s)):
        print(s[i],end="")

Submission status: Accepted

Solution code:
from collections import deque

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

qq = [list(input().split()) for i in range(q)]


rl = 1
rlrl = 1
fleft = deque()
fright = deque()

for i in qq:
  if i[0] == '1':
    rl *= -1
  else:
    if i[1] == '1':
      if rl == 1:
        fleft.appendleft(i[2])
      else:
        fright.append(i[2])
    else:
      if rl == 1:
        fright.append(i[2])
      else:
        fleft.appendleft(i[2])

fleft.reverse()        
        
s.extendleft(fleft)
s.extend(fright)        

if rl == -1:
  s.reverse()

print(''.join(s))

Submission status: Accepted

Solution code:
S = input()
Q= int(input())
r = False
h = []
t = []
for i in range(Q):
    Query = input().split()
    if int(Query[0]) == 1:
        r = not r
    else:
        if int(Query[1]) == 1 and not r or int(Query[1]) == 2 and r:
            h.append(Query[2])
        else:
            t.append(Query[2])
if not r:
    print(''.join(reversed(h))+S+''.join(t))
else:
    print(''.join(reversed(t))+S[::-1]+''.join(h))

Submission status: Accepted

Solution code:
def main():
  S = input()
  Q = int(input())
  Query=[input().split() for q in range(Q)]
  cnt=0
  prefix, suffix = '', ''
  for q in Query:
    if q[0]=='1':
      cnt=1^cnt
      prefix, suffix = suffix, prefix
      #print(cnt)
    else:
      if q[1]=='1':
        prefix=prefix+q[2]
      else:
        suffix=suffix+q[2]
  if cnt:
    S=S[::-1]
  print(prefix[::-1]+S+suffix)

main()

Submission status: Accepted

Solution code:
def resolve():
    S = input()
    Q = int(input())
    reverse = False
    import collections
    left = collections.deque([])
    right = collections.deque([])
    for i in range(Q):
        query = input().split()
        if query[0] == "1":
            reverse = (not reverse)
            continue
        if query[1] == "1":
            if reverse:
                right.append(query[2])
            else:
                left.appendleft(query[2])
        elif query[1] == "2":
            if reverse:
                left.appendleft(query[2])
            else:
                right.append(query[2])
    if reverse:
        ans = "{}{}{}".format("".join(reversed(right)), "".join(reversed(S)), "".join(reversed(left)))
    else:
        ans = "{}{}{}".format("".join(left), S, "".join(right))
    print(ans)


if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
s = input()
q = int(input())
rev = False
bef = ""
aft = ""
for _ in range(q):
    t = list(input().split())
    if t[0] == "1":
        rev = not rev
    else:
        f = t[1]
        c = t[2]
        if rev:
            if f == "1":
                aft += c
            else:
                bef += c
        else:
            if f == "1":
                bef += c
            else:
                aft += c
if rev:
    ans = aft[::-1] + s[::-1] + bef
else:
    ans = bef[::-1] + s + aft
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import sys

flg1 = 1
s = input()
ll = deque()
lr = deque()
for _ in range(int(input())):
    q = sys.stdin.readline().rstrip()
    if q == "1":
        flg1 *= -1
    else:
        q = list(q.split())
        flg2 = 1 if q[1] == "1" else -1
        if flg1 * flg2 == 1:
            ll.appendleft(q[2])
        else:
            lr.append(q[2])

ans = "".join(ll) + s + "".join(lr)
print((ans[::-1], ans)[flg1 == 1])