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:
#!python3

import sys
iim = lambda: map(int, input().rstrip().split())
from collections import deque

def resolve():
    S = deque(input().rstrip())
    Q = int(input())

    rev = False
    for ti, *arg in (line.split() for line in sys.stdin):

        if ti == "1":
            rev = not rev
        else:
            fi, ci = arg
            fi = fi == "1"
            if fi ^ rev:
                S.appendleft(ci)
            else:
                S.append(ci)
    if rev:
        S.reverse()
    print(*S, sep="")


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
query_list = []
for i in range(Q):
    query_list.append(input())
# print(S, Q, query_list)

M = 10 ** 6
start_position = int(M / 2)
left_position = start_position
right_position = start_position + len(S)
result = ["-"] * M
for i in range(len(S)):
    # print(i + left_position)
    result[i + left_position] = S[i]

# result = "".join(result[left_position:right_position])
# print(result)
# exit(0)
reverse_flag = False

for i in range(Q):
    # print(i + 1)
    # print(result[left_position:right_position])
    q = query_list[i]
    # print(q)
    t = int(q[0])
    if t == 1:
        reverse_flag = not reverse_flag
    else:
        t, f, c = q.split()
        f = int(f)
        c = c
        if f == 1:
            if reverse_flag:
                result[right_position] = c
                right_position += 1
            else:
                result[left_position - 1] = c
                left_position -= 1
        else:
            if reverse_flag:
                result[left_position - 1] = c
                left_position -= 1
            else:
                result[right_position] = c
                right_position += 1
    # print(t, f, c, result)
    # print("--------")
    #print(result[left_position:right_position])
# result = str(result)
# result = "".join(result)
# print(result)
# print(result[left_position:right_position])

result = "".join(result[left_position:right_position])
if reverse_flag:
    result = result[::-1]
print(result)

Submission status: Accepted

Solution code:
import sys

s = sys.stdin.readline().strip()

q = int(sys.stdin.readline().strip())

class Node:
    def __init__(self, c):
        self.prev = None
        self.next = None
        self.c = c
s = list(s)

head = Node(s[0])
tail = None
prev = head
for i in range(1, len(s)):
    crt = Node(s[i])
    prev.next = crt
    crt.prev = prev
    prev = crt
tail = prev

order = 0
for _ in range(q):
    l = sys.stdin.readline().strip()
    if l[0] == "1":
        order = (order + 1) %2
    else:
        t, f, c = l.split()
        n = Node(c)
        if (f == "1" and order == 0) or ( f== "2" and order==1):
            # add to head
            n.next = head
            head.prev = n
            head = n
        else:
            # add to tail
            tail.next = n
            n.prev = tail
            tail = n
if order == 0:
    crt = head
    while crt != None:
        print(crt.c, end="")
        crt = crt.next
else:
    crt = tail
    while crt != None:
        print(crt.c, end="")
        crt = crt.prev
print("")

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
QUERY = []
for i in range(Q):
    QUERY.append(input().split(' '))


def main(s, q, query):
    addflag = 'front'

    s_front = ''
    s_back = ''

    for i in range(q):
        if query[i][0] == '1':
            if addflag == 'front':
                addflag = 'back'
            elif addflag == 'back':
                addflag = 'front'
        elif query[i][0] == '2':
            if addflag == 'front' and query[i][1] == '1':
                s_front = query[i][2] + s_front
                # s = query[i][2] + s
            elif addflag == 'front' and query[i][1] == '2':
                s_back = s_back + query[i][2]
                # s = s + query[i][2]
            elif addflag == 'back' and query[i][1] == '1':
                s_back = s_back + query[i][2]
                # s = s + query[i][2]
            elif addflag == 'back' and query[i][1] == '2':
                s_front = query[i][2] + s_front
                # s = query[i][2] + s

    if addflag == 'back':
        s = ''.join(reversed(list(s)))
        s_tmp = ''.join(reversed(list(s_front)))
        s_front = ''.join(reversed(list(s_back)))
        s_back = s_tmp

    return s_front + s + s_back


print(main(S, Q, QUERY))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
from collections import deque
input = sys.stdin.readline
S=deque(input()[:-1])
Q=int(input())
r = False
for _ in range(Q):
  qs = input()[:-1].split(' ')
  if len(qs) == 1:
    r = not r
  else:
    if (qs[1] == '1' and (not r)) or (qs[1] == '2' and r):
      S.appendleft(qs[2])
    else:
      S.append(qs[2])
if r:
  print(''.join(reversed(S)))
else:
  print(''.join(S))

Submission status: Accepted

Solution code:
s = input()
totalre = 0
q = int(input())
gm = []
gu = []
for _ in range(q):
    query = list(input().split())
    if int(query[0])==1:
        totalre += 1
    else:
        if (totalre + int(query[1]))%2 != 0:
            gm.append(query[2])
        else:
            gu.append(query[2])

if totalre%2==0:
    ans = ''.join(gm)[::-1] + s + ''.join(gu)
else:
    ans = ''.join(gu)[::-1] + s[::-1] + ''.join(gm)
print(ans)

Submission status: Accepted

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

forward_flag = 1

front = ""
back = ""

for i in range(Q):
    n = list(map(str, input().split()))
#     print(n)
    
    if len(n)==1:
        if forward_flag==1:
            forward_flag = 0
        else:
            forward_flag = 1
    else:
        a, b, c = n
        if (forward_flag==1 and b=="1") or (forward_flag==0 and b=="2"):
            front += c
        else:
            back += c

if forward_flag==1:
    print(front[::-1], end="")
    print(S, end="")
    print(back)
else:
    print(back[::-1], end="")
    print(S[::-1], end="")
    print(front)

Submission status: Accepted

Solution code:
s = input()

flag = 0
cnt = 0
n = int(input())

que_ar = [input() for _ in range(n)]

f_x = ["" for _ in range(n)]
b_x = ["" for _ in range(n)]


f = n-1
b = 0

for i in range(n):
    que = que_ar[i]
    if(len(que) == 1):
        cnt += 1
    else:
        que = que.split()
        if(cnt%2 == 0):
            if(que[1]=="1"):
                f_x[f] = que[2]
                f -= 1
            else:
                b_x[b] = que[2]
                b += 1
        else:
            if(que[1]=="1"):
                b_x[b] = que[2]
                b += 1
            else:
                f_x[f] = que[2]
                f -= 1

s = "".join(f_x)+s+"".join(b_x)             
                
if(cnt%2 == 0):
    print(s)
else:
    print(s[::-1])

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
sys.setrecursionlimit(4100000)


def main():
    a = deque(input())
    a.pop()

    a_append = a.append
    a_appendleft = a.appendleft

    Q = int(input())
    count = 0
    for _ in range(Q):
        q = list(input().split())
        if q[0] == "1":
            count += 1
        else:
            if count % 2 == 0:
                if q[1] == "1":
                    a_appendleft(q[2])
                else:
                    a_append(q[2])
            else:
                if q[1] == "1":
                    a_append(q[2])
                else:
                    a_appendleft(q[2])

    b = list(a)
    if count % 2 != 0:
        b.reverse()
    print("".join(b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
def main():
  s = deque(list(input()))
  q = int(input())
  sr = s.reverse
  sa = s.append
  sal = s.appendleft

  cnt = 0
  for _ in range(q):
    t = input()
    if t[0] == "1":
      cnt += 1
    else:
      _,f,c = t.split(" ")
      if f == "1":
        if cnt%2==1:
          sa(c)
        else:
          sal(c)
      else:
        if cnt%2==1:
          sal(c)
        else:
          sa(c)
  if cnt%2 == 1:
    sr()
  print("".join(list(s)))

if __name__=="__main__":
  main()

Submission status: Accepted

Solution code:
from collections import deque
S = deque(input())
Q = int(input())
count = 0
for i in range(Q):
    l = list(input().split())
    if len(l) == 1:
        count +=1
    else:
        l[1] = int(l[1])
        if count%2 == 1:
            if l[1] == 1:
                l[1] = 2
            else:
                l[1] = 1
        if l[1] == 1:
            S.appendleft(l[2])
        else:
            S.append(l[2])

if count%2 == 0:
    print(''.join(list(S)))
else:
    S.reverse()
    print(''.join(list(S)))

Submission status: Accepted

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

def sol():
    s=input().rstrip()
    q=int(input())
    x=0
    a,b="",""
    for i in range(q):
        l=tuple([i for i in input().split()])
        if l[0]=="1":
            x=(x+1)%2
        elif l[1]=="1":
            if x==0: a=l[2]+a
            else: b=b+l[2]
        elif l[1]=="2":
            if x==0: b=b+l[2]
            else: a=l[2]+a
    s=a+s+b
    print(s if x==0 else s[::-1])

if __name__=="__main__":
    sol()

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random

# List of ints
def LI(): return list(map(int, sys.stdin.readline().split()))

# Single int
def I(): return int(sys.stdin.readline())

# List, which contains Lists of chars (not strings)
def LS():return list(map(list, sys.stdin.readline().split()))

# Single List of chars (not strings)
def S(): return list(sys.stdin.readline())[:-1]

# List of "n" integers from "n" lines.
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
# List of "n" Lists of integers
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l


# Runtime Complexity: O(?)
# Space Complexity: O(?)
# Solution
s = sys.stdin.readline().split()[0]
lines_count = I()

chars = deque(s)

def prepend(chars, ch):
    chars.appendleft(ch)

def append(chars, ch):
    chars.append(ch)

actions = {
    1: prepend,
    2: append
}

for i in range(lines_count):
    line = LS()

    if len(line) == 1:
        actions[1], actions[2] = actions[2], actions[1]
    else:
        if line[1][0] == '1':
            actions[1](chars, line[2][0])
        else:
            actions[2](chars, line[2][0])

chars = list(chars)
if actions[1] == append:
    chars.reverse()

print(''.join(chars))

Submission status: Accepted

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

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

reverse = False

mae = []
ushiro = []

for i in range(Q):
    query = input()
    if query == "1":
        reverse = not reverse

    else:
        a,b,c = list(query.split())
        if (b == "1" and not reverse) or (b == "2" and reverse):
            mae.append(c)
        else:
            ushiro.append(c)

if reverse:
    origin = [S[::-1]]
    ans = ushiro[::-1]
    ans.extend(origin)
    ans.extend(mae)
    print(''.join(ans))
else:
    ans = mae[::-1]
    origin = [S]
    ans.extend(origin)
    ans.extend(ushiro)
    print(''.join(ans))

Submission status: Accepted

Solution code:
from collections import deque

S = input()
result_string = deque(S)
Q = int(input())
reverse_flag = 1
for idx in range(Q):
  new_in = input().split()
  if len(new_in) == 1:
    reverse_flag = -1*reverse_flag
  else:
    # 1 means right, -1 means left
    side_to_append = reverse_flag*(2*int(new_in[1])-3)
    if side_to_append == 1:
      result_string.append(new_in[2])
    else:
      result_string.appendleft(new_in[2])
if reverse_flag == -1: result_string.reverse()
print("".join(result_string))

Submission status: Accepted

Solution code:

# -*- coding: utf-8 -*-

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

rev = False
S1 = ['0'] * Q
S1i = 0
S2 = ['0'] * Q
S2i = 0

for q in range(Q):
    i = input()
    if i[0] == "1":
        rev = not rev
    elif not rev and i[2] == "1" or rev and i[2] == "2":
        # S = i[4] + S
        S1[S1i] = i[4]
        S1i += 1
    else:
        # S = S + i[4]
        S2[S2i] = i[4]
        S2i += 1

S1 = S1[0:S1i]
S2 = S2[0:S2i]
S1 = S1[::-1]

S = ''.join(''.join(S1) + S + ''.join(S2))

if rev:
    S = S[::-1]

print(S)

Submission status: Accepted

Solution code:
s = input()
q = int(input())
rev_flag = False
x_lis = []
y_lis = []
for _ in range(q):
    i = input()
    if i == '1':
        rev_flag = not rev_flag
    else:
        a,b,c = i.split()
        if rev_flag:
            if b == '1':
                #s = s + c
                y_lis.append(c)
            else:
                #s = c + s
                x_lis.append(c)
        else:
            if b == '1':
                #s = c + s
                x_lis.append(c)
            else:
                #s = s + c
                y_lis.append(c)
x = ''.join(reversed(x_lis))
y = ''.join(y_lis)
if rev_flag:
    print(''.join(list(reversed(x+s+y))))
else:
    print(x+s+y)

Submission status: Accepted

Solution code:
# 先頭と末尾を保ちつつ
from collections import deque

s = input()
q = int(input())
x, y = deque(), deque()
r = 0
for _ in range(q):
    query = input().split()
    if query[0] == "1":
        r += 1
        x, y = y, x
    elif query[0] == "2":
        f, c = query[1], query[2]
        if f == "1":
            if r % 2 == 0:
                x.appendleft(c)
            else:
                x.append(c)
        elif f == "2":
            if r % 2 == 1:
                y.appendleft(c)
            else:
                y.append(c)

if r % 2 == 1:
    s = s[::-1]
    x = reversed(x)
    y = reversed(y)
print("".join(x) + s + "".join(y))

Submission status: Accepted

Solution code:
from collections import deque

S = deque(input())
n= int(input())
condition=True

for i in range(n):
  Q = [i for i in input().split()]
  if Q[0] =='1':
    if condition ==True:
      condition=False
    else:
      condition=True
  else:
    if Q[1]=='1':
      if condition ==True:
        S.appendleft(Q[2])
      else:
        S.append(Q[2])
    else:
      if condition==True:
        S.append(Q[2])
      else:
        S.appendleft(Q[2])
    #print(S)

if condition ==False:
  S.reverse()

for i in S:
  print(i, end='')

Submission status: Accepted

Solution code:
from collections import deque
S = deque(input())
N = int(input())
Q = []
gyaku = 0
for i in range(N):
    q = input()
    if len(q)>1:
        q = q.split()
    else:
        q = [q]
    Q.append(q)
#print(Q)
for i in range(N):
    if len(Q[i])==1:
        gyaku +=1
        #print(S)
    if len(Q[i])>1:
        if Q[i][1]=='1'and gyaku%2==0:
            S.appendleft(Q[i][2])
        elif Q[i][1]=='1'and gyaku%2==1:
            S.append(Q[i][2])
            #print(S)
        elif Q[i][1]=='2'and gyaku%2==0:
            S.append(Q[i][2])
        else:
            S.appendleft(Q[i][2])
            #print(S)
if gyaku%2==0:
    #print(S)
    print(''.join(S))
else:
    S = list(S)
    print(''.join(S[::-1]))

Submission status: Accepted

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

flag = False
add_after = ""
add_before = ""
for q_num in q_list:
    if int(q_num[0]) == 1:
        if flag == False:
            flag = True
        else:
            flag = False
    
    else:
        if int(q_num[1]) == 1 and flag == False or int(q_num[1]) == 2 and flag == True:
            add_before = q_num[2] + add_before
        else:
            add_after = add_after + q_num[2]

result = add_before + s + add_after
if flag:
    print(result[::-1])
else:
    print(result)

Submission status: Accepted

Solution code:
S = list(map(str, input()))
q = int(input())
Q =[list(map(str, input().split())) for k in range(q)]
rev = False
f1 = []
f2 = []
def pls(n):
    global rev
    if n[0] == "1":
        rev = not rev
    else:
        if n[1] == "1":
            if rev:
                f2.append(n[2])
            else:
                f1.append(n[2])
        else:
            if rev:
                f1.append(n[2])
            else:
                f2.append(n[2])

for k in range(q):
    pls(Q[k])

if rev:
    S.reverse()
    f2.reverse()
    ans = f2 + S + f1
else:
    f1.reverse()
    ans = f1 + S + f2

print("".join(map(str, ans)))

Submission status: Accepted

Solution code:
alph="abcdefghijklmnopqrstuvwxyz"
from collections import deque
import sys
input=sys.stdin.readline
moji=deque([])
s=input().rstrip()
for i in range(len(s)):
	for j in range(26):
		if s[i]==alph[j]:
			moji.append(j)
			break
q=int(input())
rev=0
for _ in range(q):
	qw=input().split()
	if qw[0]=="1":
		rev+=1
	else:
		f=qw[1]
		c=qw[2]
		for j in range(26):
			if c==alph[j]:
				x=j
				break
		if f=="1":
			if rev%2==0:
				moji.appendleft(x)
			else:
				moji.append(x)
		else:
			if rev%2==0:
				moji.append(x)
			else:
				moji.appendleft(x)
ans=""
r=[]
for i in range(len(moji)):
	r.append(moji.popleft())
for i in range(len(r)):
	ans+=alph[r[i]]
if rev%2==0:
	print(ans)
else:
	print(ans[::-1])

Submission status: Accepted

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

buf = [0] * (3*(10**5)+10)
for i, s in enumerate(S):
    buf[i] = s

is_reverse = False
first = 0
last = len(S) - 1

def add_top(c):
    global buf
    global first
    if is_reverse:
        first += 1
    else:
        first -= 1
    buf[first] = c

def add_tail(c):
    global buf
    global last
    if is_reverse:
        last -= 1
    else:
        last += 1
    buf[last] = c

for i in range(Q):
    Query = input().split()
    t = int(Query[0])
    if t == 1:
        is_reverse = not is_reverse
        first, last = last, first
    else:
        f = int(Query[1])
        c = Query[2]
        if f == 1:
            add_top(c)
        else:
            add_tail(c)

ans_list = []
p = first
while True:
    ans_list.append(buf[p])
    if p == last:
        break
    if is_reverse:
        p -= 1
    else:
        p += 1
ans = ''.join(ans_list)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

S = input()
Q = int(input())
L = [list(input().split()) for i in range(Q)]

hanten = 0
t = deque([S])

for l in L:
    if len(l) == 1:
        hanten += 1
    elif (l[1] == '1' and hanten % 2 == 0) or (l[1] == '2' and hanten % 2 == 1):
        t.appendleft(l[2])
    else:
        t.append(l[2])

ans = ''.join(t)
if hanten % 2 == 1:
    ans = ''.join(list(reversed(ans)))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import copy

S = list(input())
Q = int(input())
Q_list = [input().split() for i in range(Q)]

sn = 0
s = 0

Ans_list1 = deque([])

for k in range(len(S)):
    Ans_list1.append(S[k])

for j in range(Q):
    if Q_list[j][0] == "1":
        s += 1

if s % 2 == 1:
    Ans_list1.reverse()

Ans_list2 = copy.deepcopy(Ans_list1)

for i in range(Q):
    if Q_list[i][0] == "1":
        sn += 1
    else:
        if (sn % 2 == 0 and Q_list[i][1] == "1") or (sn % 2 == 1 and Q_list[i][1] == "2"):
            Ans_list1.appendleft(Q_list[i][2])
            Ans_list2.append(Q_list[i][2])
        else:
            Ans_list1.append(Q_list[i][2])
            Ans_list2.appendleft(Q_list[i][2])


if sn % 2 == 0:
    print(''.join(Ans_list1))
else:
    print(''.join(Ans_list2))

Submission status: Accepted

Solution code:
#ABC158 D - String Formation

start = str(input())
Q = int(input())
S = "X"
cnt = 0
q = []
for i in range(Q):
    q.append(input().split(' '))
    if(q[i][0] == '1'):
        #S = S[::-1]
        cnt += 1

cntq = 0
for i in range(Q):
    #q = input().split(' ')
    if(q[i][0] == '1'):
        #S = S[::-1]
        cntq += 1
 
    else:
        if((q[i][1] == '1' and (cnt-cntq)%2 == 0) or(q[i][1] == '2' and (cnt-cntq)%2 == 1)):
            S = q[i][2] + S
        else:
            S = S + q[i][2]

if(cnt%2 == 1):
    start = start[::-1]


#print(S)
print(S.replace("X",start))

Submission status: Accepted

Solution code:
s=input()
q=int(input())
query=[input() for i in range(q)]
index=0
str_list=[[],[]]
for que in query:
  if len(que)==1:
    index=not index
  else:
    _,f,c=que.split()
    str_list[index^(int(f)-1)].append(c)
bf="".join(str_list[index][::-1])
af="".join(str_list[not index])
if index:
  s=s[::-1]
print(bf+s+af)

Submission status: Accepted

Solution code:
from collections import deque
S=input()
Q=int(input())
q=deque()
for i in S:
  q.append(i)
cnt=0
for i in range(Q):
  A=list(input().split())
  if int(A[0])==1:
    cnt+=1
  else:
    if int(A[1])==cnt%2+1:
      q.appendleft(A[-1])
    else:
      q.append(A[-1])
if (cnt%2)==0:
  for i in range(len(q)):
    print(q.popleft(),end='')
else:
  for i in range(len(q)):
    print(q.pop(),end='')

Submission status: Accepted

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

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

    for i in range(q):
        q_list.append(input())

    r_flg = True
    s_str = ''
    e_str = ''

    for query in q_list:
        # query 1
        if query[0] == '1':
            r_flg = not r_flg
        
        # query 2
        else:
            # Fi = 1
            if query[2] == '1':
                if r_flg:
                    s_str = query[4] + s_str
                else:
                    e_str = e_str + query[4]
            # Fi = 2
            else:
                if r_flg:
                    e_str = e_str + query[4]
                else:
                    s_str = query[4] + s_str

        # print('cont:{}, s:{}, r_flg:{}'.format(i, s, r_flg))

    s = s_str + s + e_str

    if not r_flg:
        s = ''.join(reversed(s))

    print(s)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from itertools import chain

def swap(head, tail):
    return (tail, head)

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

head = []
tail = []
count = 0

for _i in range(q):
    query = input()
    if query == "1":
        count += 1
        head, tail = swap(head, tail)
    else:
        _n, f, c = tuple(query.split())
        if f == "1":
            head.append(c)
        else:
            tail.append(c)

s = s if count % 2 == 0 else reversed(s)
print("".join(tuple(chain(reversed(head), s, tail))))

Submission status: Accepted

Solution code:
import array
def main():
  n=2*10**5
  s=input()
  q=int(input())
  rev=0
  l=n-1
  r=n+len(s)
  s=array.array('b',[0]*n+[ord(c) for c in s]+[0]*n)
  for _ in range(q):
    query=input().split()
    if(query[0]=='1'):
      rev=1-rev
    elif((int(query[1])+rev)%2==1):
      s[l]=ord(query[2])
      l-=1
    else:
      s[r]=ord(query[2])
      r+=1
  s=[chr(c) for c in s if c!=0]
  if rev==1:
    return ''.join(s[::-1])
  return ''.join(s)
print(main())

Submission status: Accepted

Solution code:
from collections import deque


S = deque(list(input()))
Q = int(input())
queries = []
for _ in range(Q):
    query = input().split()
    if len(query) == 3:
        queries.append([int(x) for x in query[:2]] + [query[2]])
    else:
        if len(queries[-1]) == 1:
            queries.pop()
        else:
            queries.append([int(x) for x in query])
p = True
count = 0
for query in queries:
    if len(query) == 3:
        if p:
            if query[1] == 1:
                S.appendleft(query[2])
            else:
                S.append(query[2])
        else:
            if query[1] == 1:
                S.append(query[2])
            else:
                S.appendleft(query[2])
    else:
        p = not p
        count += 1

if count % 2:
    S.reverse()
print(''.join(S))

Submission status: Accepted

Solution code:
from collections import deque

s = deque(list(input()))
n = int(input())
h = 1
hantensuu = 0

def change(flag):
    if flag==1:
        return 2
    else:
        return 1

for i in range(n):
    inputs = list(input().split())
    t = int(inputs[0])

    if len(inputs) == 3:
        f = int(inputs[1])
        c = inputs[2]
    if t == 1:
        h = change(h)
        hantensuu += 1
    if t == 2:
        if (f == 1 and h == 1) or (f==2 and h==2):
            s.appendleft(c)
        if (f == 2 and h == 1) or (f==1 and h ==2):
            s.append(c)
    
if hantensuu%2 !=0:
    s.reverse()

print("".join(s))

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 7)
readline = sys.stdin.readline


def main():
    a = input()
    d = deque(a)
    n = int(input())
    flagr = 1
    for i in range(n):
        j = list(readline().split())
        if len(j) == 3 and j[1] == "1" and flagr == 1:
            d.appendleft(j[2])
        elif len(j) == 3 and j[1] == "2" and flagr == 1:
            d.append(j[2])
        elif len(j) == 3 and j[1] == "2" and flagr == -1:
            d.appendleft(j[2])
        elif len(j) == 3 and j[1] == "1" and flagr == -1:
            d.append(j[2])
        else:
            flagr *= -1
    if flagr == -1:
        d.reverse()
    ans = ""
    for j in d:
        ans = ans + j
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
if __name__ == '__main__':
    lines = sys.stdin.readlines()
    line = [a.strip('\n').split(' ') for a in lines]
    # print(line)
    right = []
    left = []
    count = 0

    for i,v in enumerate(line):
        if i == 0:
            st = v
        if i == 1:
            q = v
        if i >= 2:
            if len(v)==3:
                for j,k in enumerate(v):
                    if j == 1:
                        ichi = int(k)
                    if j==2:
                        alp = k
                if count%2 == 0:
                    if ichi == 1:
                        left.append(alp)
                        # print('left'+str(left))
                    if ichi == 2:
                        right.append(alp)
                        # print('right'+str(right))
                else:
                    if ichi == 1:
                        right.append(alp)
                        # print('right'+str(right))
                    if ichi == 2:
                        left.append(alp)
                        # print('left' + str(left))

            if len(v)==1:
                count += 1
    
    # print(left)
    # print(right)
    b = list(st[0])
    # print(list(st[0]))
    # print(b)
    # print(count)
    if count%2 == 0:
        d = list(reversed(left))+b+right
    if count%2 == 1:
        d = list(reversed(right))+list(reversed(b))+left
    print(''.join(d))

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
f = True
l = []
r = []
for _ in range(Q):
    q = input()
    if q == "1":
        f = not f
    else:
        _, F, C = q.split()
        if F == "1":
            t = l if f else r
            t.append(C)
        else:
            t = r if f else l
            t.append(C)
if f:
    l.reverse()
    ans = "".join(l) + S + "".join(r)
else:
    r.reverse()
    ans = "".join(r) + S[::-1] + "".join(l)
print(ans)

Submission status: Accepted

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

sb=""
sa=""
rev=1
for i in range(q):
    qu=input()
    if qu=="1":
        rev=-rev
    else:
        t,f,c=qu.split()
        if f=="1" and rev==1:
#            s=c+s
            sb=c+sb
#            print(s)
        elif f=="2" and rev==1:
#            s=s+c
            sa=sa+c
#            print(s)
        elif f=="1" and rev==-1:
#            s=s+c
            sa=sa+c
#            print(s)
        elif f=="2" and rev==-1:
#            s=c+s
            sb=c+sb
#            print(s)
s=sb+s+sa
if rev==-1:
    s=s[::-1]
#    print(s)
print(s)

Submission status: Accepted

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

direction = 1  # 操作を始める前の向きを1、逆を-1とする
output_string = s
string1 = ''
string2 = ''

change_direction_count = 0
for query in q_datas :
    if query[0] == '1':
        direction *= -1
        change_direction_count += 1
    else:
        if query[1] == '1' and direction == 1:
            string1 = query[2] + string1
        elif  query[1] == '1' and direction == -1:
            string2 = string2 + query[2]
        elif  query[1] == '2' and direction == 1:
            string2 = string2 + query[2]
        else: # query[1] == '2' and direction == -1
            string1 = query[2] + string1

if change_direction_count % 2 == 0:
    print(string1 + s + string2)
else:
    print(string2[::-1] + s[::-1] + string1[::-1])

Submission status: Accepted

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

S = deque([S])

for _ in range(Q):
    Query += [input()]

reversed = False
for i, q in enumerate(Query):
    if q == "1":
        reversed = not reversed
        # S = S[::-1]
    else:
        Ti, Fi, Ci = list(q.split())
        # print(f"Fi:{Fi} S:{S} reversed:{reversed} Ci:{Ci}")
        if Fi == "1":
            if not reversed:
                S.appendleft(Ci)
                # S = Ci + S
            else:
                S.append(Ci)
                # S = S + Ci
        elif Fi == "2":
            # print(f"S:{S} reversed:{reversed} Ci:{Ci}")
            if not reversed:
                S.append(Ci)
                # S = S + Ci
            else:
                S.appendleft(Ci)
                # S = Ci + S
    # print(f"i:{i} S:{S}")

s = "".join(S)

if reversed:
    print(s[::-1])
else:
    print(s)