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:
s = input()
q = int(input())

rvs = False
front = []
back = []
for i in range(q):
    op = input().split()
    if op[0] == "1":
        rvs = rvs ^ 1
    else:
        if op[1] == "1":
            if rvs:
                back.append(op[2])
            else:
                front.append(op[2])
        else:
            if rvs:
                front.append(op[2])
            else:
                back.append(op[2])

if rvs:
    for c in reversed(back):
        print(c, end='')
    for c in reversed(s):
        print(c, end='')
    for c in front:
        print(c, end='')
else:
    for c in reversed(front):
        print(c, end='')
    print(s, end='')
    for c in back:
        print(c, end='')

print()

Submission status: Accepted

Solution code:
# coding: utf-8

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


heads = {}
tails = {}
h = 0
t = 0
rev = False
for _ in range(Q):
    line = input()

    if line[0] == "1":
        rev = not rev

    else:
        if line[2] == "1":
            if rev:
                # S = "".join([S, line[4]])
                tails[t] = line[4]
                t += 1
            else:
                # S = "".join([line[4], S])
                heads[h] = line[4]
                h += 1
        else:
            if rev:
                # S = "".join([line[4], S])
                heads[h] = line[4]
                h += 1
            else:
                # S = "".join([S, line[4]])
                tails[t] = line[4]
                t += 1

head = [None] * h
tail = [None] * t

for i in range(h):
    head[i] = heads[i]
head = head[::-1]

for i in range(t):
    tail[i] = tails[i]

head_joint = "".join(head)
tail_joint = "".join(tail)
joint = "".join([head_joint, S, tail_joint])

if rev:
    print(joint[::-1])
else:
    print(joint)

Submission status: Accepted

Solution code:
from collections import deque
s=deque(list(input()))
q=int(input())
r = False
for i in range(q):
    tmp = list(input().split(' '))
    if tmp[0]=='1':
        r = not r
    elif (not r and tmp[1]=='1') or (r and tmp[1] =='2'):
        s.appendleft(tmp[2])
    else:
        s.append(tmp[2])
if not r:
    for i in s:
        print(i,end='')
else:
    for i in reversed(s):
        print(i,end='')

Submission status: Accepted

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

def main():
    s=list(input())
    r=s[:]
    r.reverse()
    ss,rr=[],[]
    n=int(input())
    flg=0
    for i in range(n):
        q=list(map(str,input().split()))
        if q[0]=='1':
            flg=(flg+1)%2
        else:
            f,c=q[1],q[2]
            if f=='1':
                if flg==0:
                    rr.append(c)
                else:
                    ss.append(c)
            else:
                if flg==0:
                    ss.append(c)
                else:
                    rr.append(c)
    if flg==1:
        ss.reverse()
        ans=''.join(ss+r+rr)
        print(ans)
    else:
        rr.reverse()
        ans=''.join(rr+s+ss)
        print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = str(input())
q = int(input())
now = True
before = str()
after = str()

for i in range(q):
    que = list(map(str,input().split()))
    if que[0] == "1":
        now = not now
    else:
        if que[1] == "1":
            if now:
                before += (que[2])
            else:
                after += (que[2])
        else:
            if not now:
                before += (que[2])
            else:
                after += (que[2])

ans = (before[::-1] + s + after)
if now:
    print(ans)
else:
    print(ans[::-1])

Submission status: Accepted

Solution code:
from collections import deque

if __name__ == '__main__':
    s = input()
    q = int(input())
    hanten_flag = 0

    d_mae = deque()
    d_ushiro = deque()

    for i in range(q):
        query = input().split(" ")
        if query[0] == "1":
            hanten_flag = (hanten_flag + 1) % 2
        else:
            if query[1] == "1":
                if hanten_flag == 0:
                    d_mae.appendleft(query[2])
                else:
                    d_ushiro.append(query[2])
            else:
                if hanten_flag == 0:
                    d_ushiro.append(query[2])
                else:
                    d_mae.appendleft(query[2])

    if hanten_flag == 0:
        print("".join(list(d_mae)) + s + "".join(list(d_ushiro)))

    else:
        print("".join(reversed(list(d_ushiro))) + s[::-1] + "".join(reversed(list(d_mae))))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
def main():
    S = input().strip()
    Q = int( input())
    Query = [ input().strip() for _ in range(Q)]
    now = 0
    ANS = deque(['1'])
    t = 0
    for q in Query:
        if q == '1':
            if now == 0:
                now = 1
            else:
                now = 0
            continue
        t += 1
        _, f, c = q.split()
        if f == '1':
            if now == 0:
                ANS.appendleft(c)
            else:
                ANS.append(c)
        else:
            if now == 0:
                ANS.append(c)
            else:
                ANS.appendleft(c)
    for i in range(t+1):
        if ANS[i] == '1':
            if now == 0:
                ANS[i] = S
            else:
                ANS[i] = S[::-1]
    if now == 1:
        ANS.reverse()
    print("".join(ANS))
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

S = deque(list(input()))
Q = int(input())
l = []
for i in range(Q):
  l.append(list(input().split()))
    
flag = 1 #1ならふつう, -1なら逆


for i in range(Q):
    if l[i][0] == "1":
        flag *= -1
    elif flag == 1:
        if l[i][1] == "1":
            S.appendleft(l[i][2])
            
        else:
            S.append(l[i][2])
            
    else:
        if l[i][1] == "2":
            S.appendleft(l[i][2])
            
        else:
            S.append(l[i][2])


if flag == 1:
    print("".join(S))
else:
    S.reverse()
    print("".join(S))

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**9)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

s = ns()
q = ni()
h = 0

from collections import deque
ss=deque(list(s))

for i in range(q):
  que = nn()
  if int(que[0]) == 1:
    h += 1
  else:
    b = int(que[1])
    c = que[2]
    if (h+b)%2 == 0:
      ss.append(c)
    else:
      ss.appendleft(c)

ss = list(ss)

if h%2 == 1:
  ss = reversed(ss)

print(''.join(ss))

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

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

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

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

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

  s=list(s)

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

# main()
print(main())

Submission status: Accepted

Solution code:
from collections import deque

s=input()

d=deque()
for i in s: #10**5
  d.append(i)
  
v=1

q=int(input())

for i in range(q): #2*10**5
  a=input()
  if len(a)==1:
    if v:
      v=0
    else:
      v=1
  else:
    b,f,c=a.split()
    if f=="1":
      if v:
        d.appendleft(c)
      else:
        d.append(c)
    else:
      if v:
        d.append(c)
      else:
        d.appendleft(c)
        
if v:
  for i in range(len(d)):
    print(d[i],end="")
else:
  for i in range(len(d)):
    print(d[len(d)-1-i],end="")
    
print()

Submission status: Accepted

Solution code:
S = list(input())
Q = int(input())
left, right = [], []
flag = 0
for q in range(Q):
    query = input().split()
    if query[0] == '1':
        flag = (flag + 1) % 2
        left, right = right, left
    else:
        F, C = query[1], query[2]
        if F == '1':
            left.append(C)
        else:
            right.append(C)
if flag == 1:
    S.reverse()
left.reverse()
left = ''.join(left)
right = ''.join(right)
S = ''.join(S)
print(left + S + right)

Submission status: Accepted

Solution code:
import sys

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

def main():
    s = read()
    pre = ""
    sur = ""
    rev = False
    for _ in range(int(read())):
        q = read()
        if q == "1":
            rev = not rev
            continue
        _, f, c = q.split()
        if rev ^ (f == "1"):
            pre += c
        else:
            sur += c
    print((pre[::-1] + s + sur)[::1 - 2 * rev])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = list(input())
q = int(input())
c = 0
s1 = []
s2 = []
for _ in range(q):
    t = input()
    if t != "1":
        t = t.split()
        if t[1] == "1":
            if c % 2 == 0:
                s1.append(t[2])
            else:
                s2.append(t[2])
        else:
            if c % 2 == 0:
                s2.append(t[2])
            else:
                s1.append(t[2])
    else:
        c += 1

if c % 2 == 0:
    s1.reverse()
    s = s1 + s + s2
else:
    s2.reverse()
    s3 = s
    s3.reverse()
    s = s2 + s3 + s1
print("".join(s))

Submission status: Accepted

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

inversion = 0
head = []
tail = []

for _ in range(Q):
    queri = input()
    if len(queri) == 1:
        inversion += 1
    else:
        _, f, c = queri.split()
        if inversion % 2 == 0 and f == "1":
            head.append(c)
        elif inversion % 2 == 1 and f == "1":
            tail.append(c)
        elif inversion % 2 == 0 and f == "2":
            tail.append(c)
        else:
            head.append(c)

#print("head={}, tail={}".format(head, tail))

if inversion % 2 == 0:
    head.reverse()
    Head = ''.join(head)
    Tail = ''.join(tail)
    print(Head + S + Tail)
else:
    tail.reverse()
    S = S[::-1]
    Head = ''.join(head)
    Tail = ''.join(tail)
    print(Tail + S + Head)

Submission status: Accepted

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

count=0
f=""
b=""

for i in range(Q):
    if q[i][0]=="1":
        count+=1
    else:
        if q[i][1]=="1":
            if count%2==0:
                f=q[i][2]+f
            else:
                b+=q[i][2]
        elif q[i][1]=="2":
            if count%2==1:
                f=q[i][2]+f
            else:
                b+=q[i][2]

if count%2==1:
    S=f+S+b
    print(S[::-1])
else:
    print(f+S+b)

Submission status: Accepted

Solution code:
from collections import deque

s = deque(input())

q = int(input())

check = 1
for _ in range(q):
    t = list(input().split())
    if t[0] == '1':
        check = 1 - check
    else:
        if t[1] == '1':
            if check == 1:
                s.appendleft(t[2])
            else:
                s.append(t[2])
        else:
            if check == 1:
                s.append(t[2])
            else:
                s.appendleft(t[2])



if check == 1:
    print(''.join(s))
else:
    s = list(reversed(s))
    print(''.join(s))

Submission status: Accepted

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

x=0
lf=[]
lb=[]

for i in range(q):
    if l[i][0]=="1":
        if x==0:
            x+=1
        else:
            x=0
    else:
        if x==0:
            if l[i][1]=="1":
                lf.append(l[i][2])
            else:
                lb.append(l[i][2])
        else:
            if l[i][1]=="1":
                lb.append(l[i][2])
            else:
                lf.append(l[i][2])


if x==0:
    for i in range(len(lf)):
        print(lf[len(lf)-i-1],end="")
    for i in range(len(s)):
        print(s[i],end="")
    for i in range(len(lb)):
        print(lb[i],end="")
else:
    for i in range(len(lb)):
        print(lb[len(lb)-i-1],end="")
    for i in range(len(s)):
        print(s[len(s)-i-1],end="")
    for i in range(len(lf)):
        print(lf[i],end="")

Submission status: Accepted

Solution code:
s=input()
qq=int(input())
re=0
l=''
r=''
f=1
for _ in range(qq):
  q=list(input().split())
  if len(q)==1:
    re+=1
    if f:
      f=0
    else:
      f=1
  else:
    t=q[2]
    if f:
      if q[1]=='1':
        l+=t
      else:
        r+=t
    else:
      if q[1]=='1':
        r+=t
      else:
        l+=t
if re%2==0:
  print(l[::-1]+s+r)
else:
  print(r[::-1]+s[::-1]+l)

Submission status: Accepted

Solution code:
from collections import deque

s = input()
que = deque(s)

T_F = True

for i in range(int(input())):
  query = input()
  if query[0] == '1':
    T_F = not T_F
  elif (query[2] == '1' and T_F) or (not query[2] == '1' and not T_F):
    que.appendleft(query[4])
  else:
    que.append(query[4])
if T_F:
  print(''.join(que))
else :
  print(''.join(reversed(que)))

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
A_1 = "" #Sの前につく文字
A_2 = "" #Sの後ろにつく文字
k = 1 #反転しているか否か
for q in range(Q):
  x_q = input()
  if x_q == "1":
    k *= -1
  else:
    [a,b,c] = x_q.rstrip().split(" ")
    if b == "1": #F_i = 1
      if k == 1:
        A_1 = c + A_1
      else:
        A_2 = A_2 + c
    else: #F_i = 2
      if k == 1:
        A_2 = A_2 + c
      else:
        A_1 = c + A_1
if k == 1:
  print(A_1 + S + A_2)
else:  
  print((A_1 + S + A_2)[::-1])

Submission status: Accepted

Solution code:
# import bisect
# from collections import Counter, deque
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd
# import itertools
# from operator import attrgetter, itemgetter
import math

import sys

# import numpy as np

ipti = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

def main():
    s = input()
    q = int(input())

    add_head = []
    add_tail = []
    is_reversed = False

    for _ in range(q):
        q = list(map(str,input().split()))
        if q[0] == "1":
            if is_reversed:
                is_reversed = False
            else:
                is_reversed = True
        else:
            if q[1] == "1":
                if is_reversed:
                    add_tail.append(q[2])
                else:
                    add_head.append(q[2])
            else:
                if is_reversed:
                    add_head.append(q[2])
                else:
                    add_tail.append(q[2])

    ans = []

    if is_reversed:
        add_head.reverse()
        ans += add_head
        ans += s
        ans += add_tail
        ans.reverse()
    else:
        add_head.reverse()
        ans += add_head
        ans += s
        ans += add_tail

    print(''.join(ans))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
deq = deque(input())
rev = False
for _ in range(int(input())):
    query = input().split()
    if query[0] == '1':
        rev = not rev
    else:
        if (query[1] == '1') ^ rev:
            deq.appendleft(query[2])
        else:
            deq.append(query[2])
if rev:
    deq.reverse()
print(''.join(deq))

Submission status: Accepted

Solution code:
from collections import deque

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

que = deque(s)
rev = 1
for qi in range(q):
    tmp = input()
    if tmp[0] == '1':
        rev *= -1
    if tmp[0] == '2':
        _, f, c = tmp.split()
        fi = 2 * (int(f) - 1) - 1
        if fi * rev == 1:
            que.append(c)
        else:
            que.appendleft(c)
lque = list(que)

if rev == 1:
    print(''.join(map(str, lque)))
    exit()

ans = ''
for i in range(len(lque)):
    ans += lque.pop()
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#整数値龍力　複数の入力
def input_multiple_number():
    return map(int, input().split())

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

preffix = ""
suffix = ""
revcnt = 0
for i in range(Q):
    query = input()
    if query[0] == "1":
        wk = preffix
        preffix = suffix
        suffix = wk
        revcnt += 1
    elif query[2] == "1":
        if revcnt %2 ==0:
            preffix = (query[4]+preffix)
        else:
            preffix += query[4]
    else:
        if revcnt %2 ==1:
            suffix = (query[4]+suffix)
        else:
            suffix += query[4]

if revcnt%2 == 1:
    S = S[::-1]
    suffix = suffix[::-1]
    preffix = preffix[::-1]


print(preffix+S+suffix)

Submission status: Accepted

Solution code:
from collections import deque

S = input()
Q = int(input())
X = [input() for _ in range(Q)]

ans = deque(S)
r = 0  # r=0: order, r=1: reverse
for i in range(Q):
    q, *x = X[i].split()
    if q == "1":
        r = abs(r - 1)
    else:
        f, c = x
        if (r == 0 and f == "1") or (r == 1 and f == "2"):
            ans.appendleft(c)
        else:
            ans.append(c)
            
print("".join(ans) if r == 0 else "".join(ans)[::-1])

Submission status: Accepted

Solution code:
S = input()
N = len(S)
Q = int(input())
sign = 1
L = ["" for i in range(N + 2 * Q)]
for i in range(N):
  L[i+Q] = S[i]
x, y = Q - 1, N + Q
for i in range(Q):
  T = list(map(str, input().split()))
  if T[0] == "1":
    sign *= -1
  else:
    F = int(T[1]) * 2 - 3
    if sign * F == 1:
      L[y] = T[2]
      y += 1
    else:
      L[x] = T[2]
      x -= 1
newS = ""
for i in range(N+2*Q):
  newS = newS[:] + L[i]
if sign == 1:
  print(newS)
else:
  M = len(newS)
  for i in range(M):
    print(newS[M-i-1], end = '')
  print()

Submission status: Accepted

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

    rule = 0
    pre, suf = '', ''
    for _ in range(q):
        query = input()
        if query[0] == '1':
            rule += 1
        else:
            if rule % 2 == 0:
                if query[2] == '1':
                    pre = query[4] + pre
                else:
                    suf += query[4]
            else:
                if query[2] == '1':
                    suf += query[4]
                else:
                    pre = query[4] + pre

    s = pre + s + suf
    print(s if rule % 2 == 0 else s[::-1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = list(input())
q = int(input())
front = []
end = []
flip = False
for i in range(q):
    x = input()
    if x == "1":
        flip = flip ^ True
    else:
        z,f,c = x.split()
        f = bool(int(f)-1)
        if flip ^ f:
            end.append(c)
        else:
            front.append(c)
if flip:
    s = s[::-1]
    ans = end[::-1] + s + front
else:
    ans = front[::-1] + s + end
print("".join(ans))

Submission status: Accepted

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

front = ''
back = ''

T_count = 0

for i in range(Q):
    command = input().split()
    if command[0] == '1':
        T_count = (T_count+1)%2
    else:
        if (int(command[1]) + T_count)%2 == 1:
            front += command[2]
        else:
            back += command[2]

if T_count == 0:
    print(front[::-1]+S+back)
else:
    print(back[::-1]+S[::-1]+front)

Submission status: Accepted

Solution code:
s = input()
q = int(input())
query = [input() for i in range(q)]
rvs = 1
s1 = ""
for i in range(q):
    if query[i] == "1":
        rvs = rvs * (-1)
    else:
        if query[i][2:3] == "1":
            if rvs == 1:
   #             s = query[i][4:5] + s
                s1 = s1 + query[i][4:5]
            else:
                s = s + query[i][4:5]
        else:
            if rvs == -1:
    #            s = query[i][4:5] + s
                s1 = s1 + query[i][4:5]
            else:
                s = s + query[i][4:5]
if rvs == -1:
    s = s[::-1] + s1
else:
    s = s1[::-1] + s
#print(rvs,s1,s)
print(s)

Submission status: Accepted

Solution code:
from collections import deque
S = list(map(str, input()))
Q = int(input())

ans_lst = deque(S)
rev = False
for i in range(Q):
  QUERY = list(map(str, input().split()))
  if QUERY[0] == '1':
    if rev:
      rev = False
    else:
      rev = True
  else:
    if rev:
      if QUERY[1] == '1':
        ans_lst.append(QUERY[2])
      else:
        ans_lst.appendleft(QUERY[2])
    else:
      if QUERY[1] == '1':
        ans_lst.appendleft(QUERY[2])
      else:
        ans_lst.append(QUERY[2])    

if rev:
  ans_lst.reverse()
  print(''.join(ans_lst))
else:
  print(''.join(ans_lst))

Submission status: Accepted

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

head = []
tail = []

mode = 0
for i in range(q):
  read = list(map(str,input().split()))
  if read[0]=='1':
    mode = (mode+1)%2
  else:
    if (read[1]=='1' and mode == 0) or (read[1]=='2' and mode == 1):
      head.append(read[2])
    else:
      tail.append(read[2])

s = head[::-1] + s
s = s + tail
if mode == 0:
  print(''.join(s))
else:
  print(''.join(s[::-1]))

Submission status: Accepted

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

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

flag = 0

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

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

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

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

print(res)

Submission status: Accepted

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


def main():
    #s = map(ord, list(readline().strip()))
    #print(s)
    s = readline().strip()
    Q = int(readline())

    queue = deque(s)
    r = 0

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

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

print(''.join(ans))

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
from collections import deque

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

d = deque(S)

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

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

    if q[0]=="1":
        cnt += 1
    
# f:奇数 cnt:偶数 先頭    
# f:奇数 cnt:奇数 後方    
# f:偶数 cnt:偶数 後方
# f:奇数 cnt:偶数 先頭
#   
    elif q[0]=="2":
        f = int(q[1])
        c = q[2]
        mm += 1

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

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

Submission status: Accepted

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

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

print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import deque


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

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

if reverce:
    s.reverse()

print("".join(s))

Submission status: Accepted

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

Submission status: Accepted

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

main()