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())
cn=0
l1=""
l2=""
for i in range(q):
    p=input()
    if p=="1":
        cn+=1
    else:
        _,f,c=p.split()
        if f=="1":
            if cn%2==0:
                l1+=c
            else:
                l2+=c
        else:
            if cn%2==1:
                l1+=c
            else:
                l2+=c
if cn%2==1:
    s=s[::-1]
    l1,l2=l2,l1
print(l1[::-1]+s+l2)

Submission status: Accepted

Solution code:
s,_,*q=open(0)
a=['',s[:-1]]
p=1
for q in q:
  try:
    q,f,c=q.split()
    a[(f<'2')^p]+=c
  except:p^=1
print(a[p^1][::-1]+a[p])

Submission status: Accepted

Solution code:
s,_,*q=open(0)
a=['',s[:-1]]
p=1
for q in q:
  if q>'2':a[(q<'2 2')^p]+=q[-2]
  else:p^=1
print(a[p^1][::-1]+a[p])

Submission status: Accepted

Solution code:
s,_,*q=open(0)
a=['',s[:-1]]
p=1
for q in q:
  q,*f=q[::2]
  if q>'1':
    f,c=f
    a[(1if f<'2'else 0)^p]+=c
  else:p^=1
print(a[p^1][::-1]+a[p])

Submission status: Accepted

Solution code:
# Problem D - String Formation

from collections import deque

# input process
S = input().replace("\n", "")
S = deque(list(S))
Q = int(input()) # query number

# initialization
sento = 1

# process
for i in range(Q):
    query_num = input()
    # クエリが１の時
    if query_num[0]=="1":
        # 反転処理
        if sento==1:
            sento = 10
        elif sento==10:
            sento = 1
    elif query_num[0]=="2":
        n, f, c = query_num.split()
        f = int(f)
        if f==1: # 先頭追加処理
            # 先頭の位置によって変わる
            if sento==1:
                S.appendleft(c)
            elif sento==10:
                S.append(c)
        elif f==2: # 末尾追加処理
            if sento==1:
                S.append(c)
            elif sento==10:
                S.appendleft(c)

# output process
if sento==1:
    print("".join(S))
else:
    print("".join(list(S)[::-1]))

Submission status: Accepted

Solution code:
s,_,*q=open(0)
a=['',s[:-1]]
p=1
for q in q:
  if q>'2':
    f=1if q<'2 2'else 0
    a[f^p]+=q[-2]
  else:p^=1
print(a[p^1][::-1]+a[p])

Submission status: Accepted

Solution code:
f=input
from collections import deque
s=deque(f())
n=int(f())
t=0
for i in range(n):
  q=f()
  if q[0]=='1': t^=1
  elif int(q[2])+t==2: s.append(q[4])
  else: s.appendleft(q[4])
print(''.join([s,list(s)[::-1]][t]))

Submission status: Accepted

Solution code:
from collections import deque
f=input
s=deque(f())
n=int(f())
t=0
for i in range(n):
  q=f()
  if q[0]=='1': t=1-t
  elif int(q[2])+t==2: s.append(q[4])
  else: s.appendleft(q[4])
print(''.join([s,list(s)[::-1]][t]))

Submission status: Accepted

Solution code:
S = input()
Slist = [S[i] for i in range(len(S))]
Q = int(input())
Query = [list(input().split()) for i in range(Q)]
Qlen = len(Query)
reverse = False
back = []
head = []

for idx, value in enumerate(Query):
    if value[0] == "1":
        reverse ^= True
        head, back = back, head
    else:
        if value[1] == "1":
            head += [value[2]]
        else:
            back += [value[2]]

if reverse == False:
    head.reverse()
    print("".join(head + Slist + back))
else:
    head.reverse()
    print("".join(head + Slist[::-1] + back))

Submission status: Accepted

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

#############
# Libraries #
#############

import math
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9 +7
INF = float('inf')

#############
# Functions #
#############

kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])
    return arr

#############
# Main Code #
#############

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

head = []
tail = []
main = []

main = list(S)

status = 0

def query():
  global head
  global tail
  global main
  global status
  l = list(map(str,input().split()))
  if l[0] == "1":
    status = (status+1)%2
  else:
    letter = l[2]
    if l[1] == "1":
      if status == 0:
        head.append(letter)
      else:
        tail.append(letter)
    else:
      if status == 0:
        tail.append(letter)
      else:
        head.append(letter)

      


while Q:
  Q -= 1
  query()

if status == 0:
  print("".join(head[::-1])+"".join(main)+"".join(tail))
else:
  print("".join(tail[::-1])+"".join(main[::-1])+"".join(head))

Submission status: Accepted

Solution code:
from collections import deque

S = deque(input())
Q = int(input())
is_reversed = False
for _ in range(Q):
    q = input().split()
    if q[0] == "1":
        is_reversed = not is_reversed
    else:
        f = int(q[1]) - 1
        if is_reversed:
            f ^= 1
        c = q[2]
        if f:
            S.append(c)
        else:
            S.appendleft(c)
if is_reversed:
    S = reversed(S)
print(*S, sep="")

Submission status: Accepted

Solution code:
def resolve():
    S = str(input())
    Q = int(input())

    rev_flag = 1
    head_str = ""
    tail_str = ""
    for _ in range(Q):
        query = input() # contains spaces
        if query[0] == "1":
            rev_flag *= -1
        else:
            h_or_t_flag = 1 if query[2] == "1" else -1
            h_or_t_flag *= rev_flag

            if h_or_t_flag == 1:
                head_str += query[4]
            else:
                tail_str += query[4]

    ans = head_str[::-1] + S + tail_str
    print(ans if rev_flag == 1 else ans[::-1])
resolve()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

S = input()
S = deque(S)
Q = INT()
flag = 1  # 1で正順
for _ in range(Q):
	q = input().split()
	if len(q) == 1:  # 前後入れ替え
		flag *= -1
	else:  # 先頭 or 末尾に追加
		_, F, C = q
		if F == "1" and flag == 1 or F == "2" and flag == -1:
			S.appendleft(C)
		else:
			S.append(C)
ans = "".join(S)
if flag == -1:
	ans = ans[::-1]
print(ans)

Submission status: Accepted

Solution code:
s = input()
n = int(input())
query = [0]*n
rev = 0
for i in range(n):
    query[i] = list(map(str, input().split()))
    if query[i][0] == '1':
        rev = rev + 1

begin = []
end = []
pal = 0

for i in range(n):
    if int(query[i][0]) == 1:
        pal = (pal+1)%2
    else:
        if pal == 0:
            if int(query[i][1]) == 1:
                begin.append(query[i][2])
            else:
                end.append(query[i][2])
        else:
            if int(query[i][1]) == 1:
                end.append(query[i][2])
            else:
                begin.append(query[i][2])
#    print('--------'+str(i+1)+'th try-----')
#    print(begin)
#    print(end)
#    print('pal:'+str(pal))
#print(s)

if rev%2 == 1:
    print(''.join(end[::-1])+s[::-1]+''.join(begin))
else:
    print(''.join(begin[::-1])+s+''.join(end))

Submission status: Accepted

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

def solve():
    d = deque(input())
    Q = int(input())

    is_reverse = False # 反転中か？

    for _ in range(Q):
        query = input()
        if query == "1":
            is_reverse = not is_reverse
        else:
            _, f, c = query.split()

            if f == "1":
                if is_reverse:
                    # 末尾にcを追加
                    d.append(c)
                else:
                    # 先頭にcを追加
                    d.appendleft(c)
            else:
                if is_reverse:
                    # 先頭に追加
                    d.appendleft(c)
                else:
                    # 末尾に追加
                    d.append(c)

    if is_reverse:
        print("".join(reversed(list(d))))
    else:
        print("".join(d))


def solve2():
    S = list(input())
    Q = int(input())
    M = 2*10**5+10
    data = [None]*M
    data.extend(S)
    data.extend([None]*M)
    left, right = M-1, M+len(S)

    is_reverse = False

    for _ in range(Q):
        query = input()
        if query == "1":
            is_reverse = not is_reverse
        else:
            t, f, c = query.split()
            if f == "1":
                if is_reverse:
                    # 末尾にcを追加
                    data[right] = c
                    right += 1
                else:
                    # 先頭にcを追加
                    data[left] = c
                    left -= 1
            else:
                if is_reverse:
                    # 先頭に追加
                    data[left] = c
                    left -= 1
                else:
                    # 末尾に追加
                    data[right] = c
                    right += 1

    # 出力
    if is_reverse:
        print("".join(data[right-1:left:-1]))
        # for i in range(right-1, left, -1):
        #     print(data[i], end="")
    else:
        # for i in range(left+1, right):
        #     print(data[i], end="")
        print("".join(data[left+1:right]))
    # print()


if __name__ == "__main__":
    solve2()

Submission status: Accepted

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

def solve():
    d = deque(input())
    Q = int(input())

    is_reverse = False # 反転中か？

    for _ in range(Q):
        query = input()
        if query == "1":
            is_reverse = not is_reverse
        else:
            _, f, c = query.split()

            if f == "1":
                if is_reverse:
                    # 末尾にcを追加
                    d.append(c)
                else:
                    # 先頭にcを追加
                    d.appendleft(c)
            else:
                if is_reverse:
                    # 先頭に追加
                    d.appendleft(c)
                else:
                    # 末尾に追加
                    d.append(c)

    if is_reverse:
        print("".join(reversed(list(d))))
    else:
        print("".join(d))


def solve2():
    S = list(input())
    Q = int(input())
    M = 2*10**5+10
    data = [None]*M
    data.extend(S)
    data.extend([None]*M)
    left, right = M-1, M+len(S)

    is_reverse = False

    for _ in range(Q):
        query = input()
        if query == "1":
            is_reverse = not is_reverse
        else:
            t, f, c = query.split()
            if f == "1":
                if is_reverse:
                    # 末尾にcを追加
                    data[right] = c
                    right += 1
                else:
                    # 先頭にcを追加
                    data[left] = c
                    left -= 1
            else:
                if is_reverse:
                    # 先頭に追加
                    data[left] = c
                    left -= 1
                else:
                    # 末尾に追加
                    data[right] = c
                    right += 1

    # 出力
    if is_reverse:
        print("".join(data[right-1:left:-1]))
        # for i in range(right-1, left, -1):
        #     print(data[i], end="")
    else:
        # for i in range(left+1, right):
        #     print(data[i], end="")
        print("".join(data[left+1:right]))
    # print()


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
# D - String Formation
import sys
from collections import deque

readline = sys.stdin.readline
readlines = sys.stdin.readlines


def main():
    S = readline().rstrip()
    _ = readline()
    queries = readlines()
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = 0
    for query in queries:
        if query[0] == "1":
            # to_beginning, to_end = to_end, to_beginning
            is_reversed ^= 1
            continue
        com, c = query[2], query[4]
        if (com == "1") ^ is_reversed:
            to_beginning(c)
        else:
            to_end(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
s = input().replace("\n", "")
s = deque(list(s))
q = int(input())
r = 0
for _ in range(q):
    t = input().split()
    if t[0] == "1":
        r = (r + 1) % 2
    else :
        if t[1] == "1":
            if r == 0:
                s.appendleft(t[2])
            else:
                s.append(t[2])
        else:
            if r == 0:
                s.append(t[2])
            else:
                s.appendleft(t[2])

if r == 0:
    print("".join(s))
else:
    print("".join(list(s)[::-1]))

Submission status: Accepted

Solution code:
from collections import deque

s = input()
n = int(input())
query = [0]*n
rev = 0
for i in range(n):
    query[i] = list(map(str, input().split()))
    if query[i][0] == '1':
        rev = rev + 1

begin = deque()
end = deque()
pal = 0

for i in range(n):
    if int(query[i][0]) == 1:
        pal = (pal+1)%2
    else:
        if pal == 0:
            if int(query[i][1]) == 1:
                begin.appendleft(query[i][2])
            else:
                end.append(query[i][2])
        else:
            if int(query[i][1]) == 1:
                end.append(query[i][2])
            else:
                begin.appendleft(query[i][2])
#    print('--------'+str(i+1)+'th try-----')
#    print(begin)
#    print(end)
#    print('pal:'+str(pal))
#print(s)

if rev%2 == 1:
    print(''.join(deque(reversed(end)))+s[::-1]+''.join(deque(reversed(begin))))
else:
    print(''.join(begin)+s+''.join(end))

Submission status: Accepted

Solution code:
from collections import deque

S = input()

q = deque(S)
forward = True
for _ in range(int(input())):
    TFC = input().split()
    if TFC[0] == '1':
        forward = not forward
    else:
        if (TFC[1] == '1') == forward:
            q.appendleft(TFC[2])
        else:
            q.append(TFC[2])

if not forward:
    q.reverse()

print(''.join(q))

Submission status: Accepted

Solution code:
# D - String Formation
import sys
from collections import deque

readline = sys.stdin.readline
readlines = sys.stdin.readlines


def main():
    S = readline().rstrip()
    _ = readline()
    queries = readlines()
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = 0
    for query in queries:
        if query[0] == "1":
            to_beginning, to_end = to_end, to_beginning
            is_reversed ^= 1
            continue
        com, c = query[2], query[4]
        if com == "1":
            to_beginning(c)
        else:
            to_end(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
s = input()
q = int(input())
ans = deque(s)
rev = 0
for i in range(q):
    qi = input()
    if qi[0] == '1':
        rev += 1
    else:
        if (int(qi[2]) + rev%2) % 2:
            ans.appendleft(qi[4])
        else:
            ans.append(qi[4])

if rev % 2:
    ans.reverse()
for i in ans:
    print(i, end='')

Submission status: Accepted

Solution code:
from collections import deque
s = input()
q = int(input())
ans = deque(s)
rev = 0
for i in range(q):
    qi = input()
    if qi[0] == '1':
        rev += 1
    else:
        parity = rev % 2
        if (int(qi[2]) + parity) % 2:
            ans.appendleft(qi[4])
        else:
            ans.append(qi[4])

parity = rev % 2
if parity:
    ans.reverse()
for i in ans:
    print(i, end='')

Submission status: Accepted

Solution code:
import sys
i = sys.stdin.read().split('\n')[:-1]
s = i[0]
a = ['', '']
r = 0
for l in i[2:]:
    if l[0] == '1':
        r ^= 1
    else:
        t, f, c = l.split()
        a[0 if f == '21'[r] else 1] += c 
if r:
    print(a[0][::-1] + s[::-1] + a[1])
else:
    print(a[1][::-1] + s + a[0])

Submission status: Accepted

Solution code:
from collections import deque
s=deque(input().split())
f=False
for i in range(int(input())):
  _=input().split()
  if _[0]=='1':
    f=not f
  elif _[1]=='1':
    if f:
      s.append(_[2])
    else:
      s.appendleft(_[2])
  else:
    if f:
      s.appendleft(_[2])
    else:
      s.append(_[2])
print("".join(s)[::-1] if f else "".join(s))

Submission status: Accepted

Solution code:
s = input()
q = int(input())
rev = False
L = ""
R = ""
for _ in range(q):
    query = input()
    if query == "1":
        rev = not rev
    else:
        _, f, c = query.split(" ")
        if f == "1":
            if rev:
                R = R + c
            else:
                L = c + L
        else:
            if rev:
                L = c + L
            else:
                R = R + c

if rev:
    s = s[::-1]
    L = L[::-1]
    R = R[::-1]
    print(R + s + L)
else:
    print(L + s + R)

Submission status: Accepted

Solution code:
s=input()
q=int(input())
cn=0
l1=""
l2=""
for i in range(q):
    p=input()
    if p=="1":
        cn+=1
    else:
        _,f,c=p.split()
        if f=="1":
            if cn%2==0:
                l1+=c
            else:
                l2+=c
        else:
            if cn%2==1:
                l1+=c
            else:
                l2+=c
if cn%2==1:
    s=s[::-1]
    l1,l2=l2,l1
print(l1[::-1]+s+l2)

Submission status: Accepted

Solution code:
import sys
s = input()
q = int(input())
a = ['', '']
r = 0
for i in range(q):
    l = sys.stdin.readline()
    if l[0] == '1':
        r ^= 1
    else:
        t, f, c = l.split()
        a[0 if f == '21'[r] else 1] += c 
if r:
    print(a[0][::-1] + s[::-1] + a[1])
else:
    print(a[1][::-1] + s + a[0])

Submission status: Accepted

Solution code:
# D - String Formation
from collections import deque


def main():
    S = input().rstrip()
    Q = int(input())
    queue = deque(S)
    is_reversed = 0
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            is_reversed ^= 1
            continue
        com, c = query[1], query[2]
        if com == "1":
            if not is_reversed:
                queue.appendleft(c)
            else:
                queue.append(c)
        else:
            if not is_reversed:
                queue.append(c)
            else:
                queue.appendleft(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
 
S = list(input())
Q = int(input())
is_forward = True
lia = []
lib = []
 
for i in range(Q):
    query = input()
 
    if query == '1':
        is_forward = not is_forward
    else:
        T, F, C = query.split()
        if is_forward:
            if F == '1':
                lia.append(C)
            else:
                lib.append(C)
        else:
            if F == '1':
                lib.append(C)
            else:
                lia.append(C)

if is_forward:
  lia.reverse()
  print(''.join(lia + S + lib))
else:
  S.reverse()
  lib.reverse()
  print(''.join(lib + S + lia))

Submission status: Accepted

Solution code:
# coding: utf-8
S = input()
Q = int(input())
# print("S:", S, "Q:", Q)

lst = [input() for _ in range(Q)]
# print("lst:", lst)
flg = True
# print("S:", S)
left = ""
right = ""
for i in lst:
    if i[0] == '1':
        flg = not flg
    else:
        if flg == False:
            if i[2] == '1':
                right = right + i[4] 
                # print("right:", right)
            else:
                left = i[4] + left
                # print("left:", left)
        else:
            if i[2] == '1':
                left = i[4] + left
                # print("left:", left)
            else:
                right = right + i[4]
                # print("right:", right)
S = left + S + right
if flg == False:
    print(S[::-1])
else:
    print(S)

Submission status: Accepted

Solution code:
from collections import deque

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

rev = False
for _ in range(q):
    query = list(input().split())
    t = query[0]
    if t == "1":
        rev = not rev
    else:
        f = int(query[1])
        c = query[2]
        if rev:
            f = 3 - f
        if f == 1:
            s.appendleft(c)
        else:
            s.append(c)
if rev:
    s.reverse()
print(''.join(s))

Submission status: Accepted

Solution code:
# D - String Formation
from collections import deque


def main():
    S = input().rstrip()
    Q = int(input())
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = 0
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            to_beginning, to_end = to_end, to_beginning
            is_reversed ^= 1
            continue
        com, c = query[1], query[2]
        if com == "1":
            to_beginning(c)
        else:
            to_end(c)
    ans = "".join(queue)
    if is_reversed:
        ans = ans[::-1]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - String Formation
from collections import deque


def main():
    S = input().rstrip()
    Q = int(input())
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = False
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            to_beginning, to_end = to_end, to_beginning
            is_reversed = not is_reversed
            continue
        com, c = query[1], query[2]
        if com == "1":
            to_beginning(c)
        else:
            to_end(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

s = deque(list(input()))
n = int(input())
f = True

for i in range(n):
    a = input()
    if a == "1":
        f = not f
    else:
        b,c,d = a.split()
        if f:
            if c == "1":
                s.appendleft(d)
            else:
                s.append(d)
        else:
            if c == "1":
                s.append(d)
            else:
                s.appendleft(d)

if not f:
    s.reverse()

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

Submission status: Accepted

Solution code:
# D - String Formation
from collections import deque


def main():
    S = input().rstrip()
    Q = int(input())
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = 0
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            is_reversed ^= 1
            continue
        com, c = query[1], query[2]
        if com == "1":
            if not is_reversed:
                to_beginning(c)
            else:
                to_end(c)
        else:
            if not is_reversed:
                to_end(c)
            else:
                to_beginning(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - String Formation
from collections import deque


def main():
    S = input().rstrip()
    Q = int(input())
    queue = deque(S)
    to_beginning, to_end = queue.appendleft, queue.append
    is_reversed = 0
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            to_beginning, to_end = to_end, to_beginning
            is_reversed ^= 1
            continue
        com, c = query[1], query[2]
        if com == "1":
            to_beginning(c)
        else:
            to_end(c)
    ans = "".join(queue) if not is_reversed else "".join(reversed(queue))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
  from collections import deque
  s=deque(input())
  q=int(input())
  count=0
  for _ in [0]*q:
    a=list(input().split())
    if len(a)==1:
      count+=1
    else:
      if count%2==0:
        if a[1]=='1':
           s.appendleft(a[2])
        else:
          s.append(a[2])
      else:
        if a[1]=='1':
          s.append(a[2])
        else:
          l=(a[2],s)
          s.appendleft(a[2])
  if count%2==1:
    s=list(s)[::-1]
  print(''.join(s))
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
pre_rev, suf = '', ''
rev = False
for _ in range(Q):
    query = input().split()
    if query[0] == '1':
        rev ^= 1
    else:
        f, c = query[1:]
        if (f == '1' and not rev) or (f == '2' and rev): pre_rev = pre_rev + c
        else: suf = suf + c
print(pre_rev[::-1] + S + suf if not rev else (S + suf)[::-1] + pre_rev)

Submission status: Accepted

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

fflag = 0
ato = ""
mae = ""
for i in range(q):
  qi = input()
  if( qi == "1"):
    fflag += 1 
  else:
    if( fflag%2 == 0 ):
      if( qi[2] == "2" ):
        ato += qi[4]
      else:
        mae += qi[4]
    else:
      if( qi[2] == "2" ):
        mae += qi[4]
      else:
        ato += qi[4]      
    
a = mae[::-1] + a + ato    
    
if( fflag%2==0 ):
  print( a )
else:
  print( a[::-1] )

Submission status: Accepted

Solution code:
from collections import deque

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

flg = 1
for _ in range(q):
    t = input()
    if t == "1":
        flg = not flg
    elif t[0] == "2":
        f = t[2]
        if f == "1":
            c = t[4]
            if flg:
                s.appendleft(c)
            else:
                s.append(c)
        elif f == "2":
            c = t[4]
            if flg:
                s.append(c)
            else:
                s.appendleft(c)

if flg:
    print(''.join(s))
else:
    print(''.join(reversed(s)))

Submission status: Accepted

Solution code:
from collections import deque
s = input()
q = int(input())
ans = deque(s)
rev = 0
for i in range(q):
    qi = input()
    if qi[0] == '1':
        rev += 1
    else:
        if qi[2] == '1' and rev % 2 == 0:
            ans.appendleft(qi[4])
        elif qi[2] == '2' and rev % 2 == 0:
            ans.append(qi[4])
        if qi[2] == '1' and rev % 2 == 1:
            ans.append(qi[4])
        elif qi[2] == '2' and rev % 2 == 1:
            ans.appendleft(qi[4])

parity = rev % 2
if parity:
    ans.reverse()
    for i in ans:
        print(i, end='')
else:
    for i in ans:
        print(i, end='')

Submission status: Accepted

Solution code:
S = list(input())
Q = int(input())
rev = False
F = []

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

    if X[0] == "1" and rev is False:
        rev = True
    elif X[0] == "1" and rev is True:
        rev = False
    elif X[0] == "2" and X[1] == "1" and rev is False:
        F.append(X[2])
    elif X[0] == "2" and X[1] == "1" and rev is True:
        S.append(X[2])
    elif X[0] == "2" and X[1] == "2" and rev is False:
        S.append(X[2])
    elif X[0] == "2" and X[1] == "2" and rev is True:
        F.append(X[2])

F.reverse()
F.extend(S)

if rev is True:
    F.reverse()

print(*F, sep="")

Submission status: Accepted

Solution code:
s = input()
n = int(input())
rev = 0
rev_check = False
first = list()
last = list()
for i in range(n):
    q = list(input().split())
    if q[0] == "1":
        rev += 1
        rev_check = not rev_check
    else:
        if rev_check ==  True:
            if q[1] == "1":
                last.append(q[2])
            else:
                first.append(q[2])
        else:
            if q[1] == "1":
                first.append(q[2])
            else:
                last.append(q[2])
if rev_check == False:
    print("".join(reversed(first)) + s + "".join(last))
else:
    print("".join(reversed(last)) + s[::-1] + "".join(first))

Submission status: Accepted

Solution code:
s = input()
q = int(input())
inv = False
left =''
right = ''

for i in range(1, q+1):
    try:
        t, f, c = input().split()
    except ValueError:
        t = '1'
    if t == '1':
        inv = not inv
    else:
        if inv:
            if f == '1':
                right = right + c
            else:
                left = c + left
        else:
            if f == '1':
                left = c + left
            else:
                right = right + c
#     print('%s, %s, %s, %s, %s' %(left, right, inv, t, f))

# # print(left)
# # print(right)
if inv:
    right = right[::-1]
    left = left[::-1]
    s = s[::-1]
    print(right + s + left)
else:
    print(left + s + right)

Submission status: Accepted

Solution code:
s,_,*q=open(0)
a=['','']
p=1
for q in q:
  p^=q<'2'
  a[(q<'2 2')^p]+=q[-2]*(q>'2')
print(a[p^1][::-1]+s[:-1][::p or-1]+a[p])