Problem:


Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

1 \leq Q \leq 2 \times 10^5

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy



Sample input:
a
4
2 1 p
1
2 2 c
1


Sample output:
cpa

Submission status: Accepted

Solution code:
from collections import deque

def resolve():
    S = deque(input())
    Q = int(input())
    query = [ input().split() for _ in range(Q)]

    sw = True
    for q in query:
        if q[0] == "2":
            if q[1] == "1":
                if sw:
                    S.appendleft(q[2])
                else:
                    S.append(q[2])
            else:
                if sw:
                    S.append(q[2])
                else:
                    S.appendleft(q[2])
        else:
            sw = not sw
    
    if not sw:
        S.reverse()
    print("".join(S))

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
inv = 0
s0 = ""
s1 = ""
for i in range(Q):
  q = input()
  if q[0] == "1":
    if inv == 0: inv = 1
    else: inv = 0
  else:
    q,f,c = q.split()
    if f == "1":
      if inv == 0:
        s0 += c
      else:
        s1 += c
    else:
      if inv == 1:
        s0 += c
      else:
        s1 += c
if inv == 1:
  S = s1[::-1] + S[::-1] + s0
else:
  S = s0[::-1] + S + s1

print(S)

Submission status: Accepted

Solution code:
def solve(s, q, query_list):
    flag = 1
    add_right = []
    add_left = []
    for i in range(q):
        query = query_list[i]
        if len(query) == 1:
            flag *= -1
        else:
            if query[1] == "1":
                if flag == 1:
                    add_left.append(query[2])
                else:
                    add_right.append(query[2])
            else:
                if flag == 1:
                    add_right.append(query[2])
                else:
                    add_left.append(query[2])
    s = "".join(list(reversed(add_left))) + s + "".join(add_right)
    # print(s, flag)
    if flag == 1:
        return s
    else:
        return "".join(list(reversed(s)))


def main():
    s = input()
    q = int(input())
    query_list = [list(input().split()) for _ in range(q)]
    res = solve(s, q, query_list)
    print(res)


def test():
    assert solve("a", 4, [["2", "1", "p"], ["1"], ["2", "2", "c"], ["1"]]) == "cpa"
    assert solve("a", 6, [["2", "2", "a"], ["2", "1", "b"], ["1"], ["2", "2", "c"], ["1"], ["1"]]) == "aabc"
    assert solve("y", 1, [["2", "1", "x"]]) == "xy"


if __name__ == "__main__":
    test()
    main()

Submission status: Accepted

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

add_texts = ["", ""]
head = 0
for q_i in query:
    if q_i[0] == "1":
        head = ~head
    else:
        f, c = q_i[1:]
        if f == "1":
            add_texts[head] += c
        else:
            add_texts[~head] += c

text = add_texts[0][::-1] + s + add_texts[1]
print(text[::[1, -1][head]])

Submission status: Accepted

Solution code:


from collections import deque


def submit():
    s = input()

    # 出来上がる文字列をdequeで管理
    curr = deque()
    for c in s:
        curr.append(c)

    # 先頭sideを管理する 1 = left, -1 = right
    front = 1

    # Queryを処理する
    q = int(input())
    for _ in range(q):
        query = input()
        if query[0] == '1':
            front *= -1
        else:
            _, f, c = query.split()
            if f == '1': # 先頭にcを追加
                if front == 1: # 先頭はleft
                    curr.appendleft(c)
                else:
                    curr.append(c)
            else:   # 末尾にcを追加
                if front == 1: #末尾はright
                    curr.append(c)
                else:
                    curr.appendleft(c)

    # 出力処理
    results = ""
    while len(curr) > 0:
        if front == 1:
            results += curr.popleft()
        else:
            results += curr.pop()

    print(results)
        


if __name__ == "__main__":
    submit()

Submission status: Accepted

Solution code:
S=input()
Q=int(input())
Rev=False
a=[]
b=[]
for _ in range(Q):
    q=list(input().split())
    if len(q)==1:
        Rev=not Rev
    else:
        if q[1]=='1':
            if not Rev:
                a.append(q[2])
            else:
                b.append(q[2])
        else:
            if Rev:
                a.append(q[2])
            else:
                b.append(q[2])
S=''.join(a)[::-1]+S+''.join(b)
if Rev:
    S=S[::-1]
print(S)

Submission status: Accepted

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

pre = ""
suf = ""
f = 1
for i in range(N):
  Q = input()
  if Q[0] == "1":
    f *= -1
  elif Q[2] == "1":
    if f > 0:
      pre = Q[4] + pre
    else:
      suf = suf + Q[4]
  else:
    if f < 0:
      pre = Q[4] + pre
    else:
      suf = suf + Q[4]

ans = pre + S + suf
if f > 0:
  print(ans)
else:
  print(ans[::-1])

Submission status: Accepted

Solution code:
from collections import deque
aa = list(map(str, input()))
S = deque()
for a in aa:
	S.append(a)
Q = int(input())
ope = []

for _ in range(Q):
	a = list(map(str, input().split()))
	if len(a) == 1:
		ope.append(a)
	else:
		ope.append(a)
	
# 先頭か末尾かを判定していけばよい
std = True # 順列か否か

for i in range(Q):
	if ope[i][0] == "1":
		std = not std
	else:
		if ope[i][1] == "1": # 先頭に付加
			if std: S.appendleft(ope[i][2])
			else: S.append(ope[i][2])
		else: # 末尾に不可
			if std: S.append(ope[i][2])
			else: S.appendleft(ope[i][2])
		
if std:		
	for s in S:
		print(s, end = "")
else:
	for s in reversed(S):
		print(s, end = "")

Submission status: Accepted

Solution code:
import copy

import math
import fractions

def j(n):
    if n:print("Yes")
    else:print("No")
    exit(0)
rem = 10 ** 9 + 7

"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def iprow():
    return [int(i) for i in input().split()]
def ips():
    return (int(i) for i in input().split())
def ipmultiplerow(n):
    a = []
    for i in range(n):
        a.append(ip())
    return a
def printrow(a):
    for i in a:
        print(i)

def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)

s = input()
n = ip()
addedleft = []
addedright = []
flip = 0
for i in range(n):
    cmd = input().split()
    #print(cmd)
    if len(cmd) == 1:
        flip+=1
        flip%=2
    else:
        if cmd[1] == "1":
            if flip == 0: addedleft.append(cmd[2])
            else: addedright.append(cmd[2])
        else: #cmd[2] == 2
            if flip == 0: addedright.append(cmd[2])
            else: addedleft.append(cmd[2])
#print("left", addedleft)
#print("right", addedright)
addedleft.reverse()
r = ''.join(addedright)
l = ''.join(addedleft)
ans  = ''.join([l,s,r])
if flip==0:
    print(ans)
else:
    for i in range(len(ans)):
        print(ans[-i-1],end='')

Submission status: Accepted

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

import sys
from collections import deque

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

S = input()

que = deque(S)
is_rev = 0
for _ in range(INT()):
    q = input().split()
    if q[0] == '1':
        is_rev = 1 - is_rev
    else:
        _, a, c = q
        a = int(a)
        if (a == 1) ^ (not is_rev):
            que.append(c)
        else:
            que.appendleft(c)
ans = ''.join(que)
if is_rev:
    ans = ans[::-1]
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

reverseFlag = 0

for _ in range(q):
    query = input().strip()
    if query[0] == "1":
        reverseFlag = 1 - reverseFlag
    else:
        lf = reverseFlag + int(query[2])
        if lf % 2 == 0:
            s.append(query[4])
        else:
            s.appendleft(query[4])

if reverseFlag == 1:
    s.reverse()
print("".join(s))

Submission status: Accepted

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

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

S = deque(input())

Q = int(input())
TURN = False

for _ in range(Q):
    q = input()
    if q[0] == '1':
        TURN = not TURN
        continue

    _, f, c = q.split()

    FIRST = True if f == '1' else False

    if (FIRST and (not TURN)) or ((not FIRST) and TURN):
        S.appendleft(c)
    else:
        S.append(c)


if TURN:
    S.reverse()

print(''.join(S))

Submission status: Accepted

Solution code:
s = input()
q = int(input())
reverse_now = 0
first = ""
latter = ""
for i in range(q):
    k = list(input().split())
    if k[0] == "1":
        reverse_now = 1 - reverse_now
    else:
        f,c = k[1], k[2]
        if f == "1" and reverse_now == 0:
            first = c + first
        if f == "1" and reverse_now == 1:
            latter += c
        if f == "2" and reverse_now == 0:
            latter +=  c
        if f == "2" and reverse_now == 1:
            first = c + first
if reverse_now == 1:
    ans = list(first + s + latter)
    ans.reverse()
    ans = "".join(ans)
else:
    ans = first + s + latter
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
s = input()
s = deque(list(s))
q = int(input())
inv=False
for _ in range(q):
    query = input()
    if query == '1':
        inv=not(inv)
    else:
        _q,f,c = query.split()
        if inv:
            if f=='2':
                s.appendleft(c)
            else:
                s.append(c)
        else:
            if f=='1':
                s.appendleft(c)
            else:
                s.append(c)

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

Submission status: Accepted

Solution code:
s = input()
back = ""
q = int(input())
rev = False
for i in range(q):
    inpt = input().split( )
    if len(inpt)>1:
        fi,ci = inpt[1],inpt[2]
        if not ((fi == "1") ^ rev):
            s += ci
        else:
            back += ci
    else:
        rev = not rev
back = back[::-1]
ans = back+s
if not rev:
    print(ans)
else:
    ans = ans[::-1]
    print(ans)

Submission status: Accepted

Solution code:
def main():
    import numpy as numpy
    import sys
    from collections import deque

    S=sys.stdin.readline().strip()
    Q=int(sys.stdin.readline())
    rv=False
    S=deque(S)
    for i in range(Q):
        qs=sys.stdin.readline().split()
        if int(qs[0])==1:
            rv=(rv+1)%2
        elif int(qs[0])==2:
            if (int(qs[1])-1+rv)%2==0:
                S.appendleft(qs[2])
            elif (int(qs[1])-1+rv)%2==1:
                S.append(qs[2])
            else:
                print('error')
                return
        else:
            print('error')
            return
    
    if rv:
        S=reversed(list(S))
    else:
        S=list(S)

    S="".join(S)
    
    return S

print(main())

Submission status: Accepted

Solution code:
from collections import deque

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

inverted = False

for _ in range(q):
  query = input()
  if query[0] == "1":
    inverted = not inverted 
  else:
    ti, fi, ci = query.split()
    if fi == "1" and inverted:
      s_queue.append(ci)
    elif fi == "1" and not inverted:
      s_queue.appendleft(ci)
    elif fi == "2" and inverted:
      s_queue.appendleft(ci)
    else:
      s_queue.append(ci)

if inverted:
  print("".join(s_queue)[::-1])
else:
  print("".join(s_queue))

Submission status: Accepted

Solution code:
from collections import deque
s=input()
q=int(input())
#反転操作はまとめてする
#2の操作が入れ替わるだけ
check=True
d=deque(list(s))
for i in range(q):
    x=input().split()
    if len(x)==1:
        check=(not check)
    else:
        t,f,c=x
        f=int(f)
        if check:
            if f==1:
                d.appendleft(c)
                #s=c+s
            else:
                d.append(c)
                #s=s+c
        else:
            if f==2:
                d.appendleft(c)
                #s=c+s
            else:
                d.append(c)
                #s=s+c

if check:
    print("".join(list(d)))
else:
    print("".join(list(d)[::-1]))

Submission status: Accepted

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    rev = 0
    sdeq = collections.deque()
    for s in S:
        sdeq.append(ord(s) - ord('a'))

    for i in range(Q):
        A = [x for x in input().split()]
        if len(A) == 1:
            rev = (rev + 1) % 2
        else:
            f = int(A[1])
            c = A[2]
            if f == 1:
                if rev == 0:
                    sdeq.appendleft(ord(c) - ord('a'))
                else:
                    sdeq.append(ord(c) - ord('a'))
            else:
                if rev == 0:
                    sdeq.append(ord(c) - ord('a'))
                else:
                    sdeq.appendleft(ord(c) - ord('a'))

    if rev == 0:
        for i in list(sdeq):
            print(chr(i + ord('a')), end="")
    else:
        for i in list(sdeq)[::-1]:
            print(chr(i + ord('a')), end="")
    print()



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()
f = ""
b = ""

rev = False

for i in range(int(input())):
  t = input().split()
  if t[0] == "1":
    rev ^= True
    tmp = f
    f = b
    b = tmp
  elif t[1] == "1":
    f += t[2]
  else:
    b += t[2]

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

f = f[::-1]
print(f + S + b)

Submission status: Accepted

Solution code:
import collections

def solve(S, Q, queries):
    S = collections.deque(S)
    is_reversed = False
    for q in queries:
        if q[0] == "1":
            is_reversed = not is_reversed
        else:
            _, f, c = tuple(q.split(" "))

            if is_reversed:
                f = "2" if f == "1" else "1"

            if f == "1":
                S.appendleft(c)
            else:
                S.append(c)

    if is_reversed:
        S = reversed(S)

    return "".join(S)

if __name__ == "__main__":
    S = input()
    Q = int(input())
    queries = []
    for _ in range(Q):
        queries.append(input())

    print(solve(S, Q, queries))

Submission status: Accepted

Solution code:
S = input()
r = False
L = []
R = []
for _ in range(int(input())):
    q = input().split()
    if q[0] == "1":
        r = not r
    else:
        if q[1] == "1":
            if r:
                R.append(q[2])
            else:
                L.append(q[2])
        else:
            if r:
                L.append(q[2])
            else:
                R.append(q[2])


if r:
    R.reverse()
    print("".join(R + list(S[::-1]) + L))
else:
    L.reverse()
    print("".join(L + [S] + R))

Submission status: Accepted

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

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

cur=True
front=""
back=""
for i in range(Q):
  q=list(readline().rstrip().split())
  if q[0]=="1":
    cur^=True
  elif q[0]=="2":
    f,c=q[1],q[2]
    if f=="1":
      if cur:
        front+=c
      else:
        back+=c
    elif f=="2":
      if cur:
        back+=c
      else:
        front+=c
front=front[::-1]
ans=front+S+back
if not cur:
  ans=ans[::-1]
  
print(ans)

Submission status: Accepted

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

A = [[], []] # 先頭、末尾
a = 0
for i in range(q):
    b = int(Q[i][0])
    if b == 1:
        a = (a+1) % 2
    else:
        f = int(Q[i][1])
        c = Q[i][2]
        A[(f-1+a)%2].append(c)
# print(A)

ANS = [A[0][i] for i in range(len(A[0])-1,-1,-1)] + s + [A[1][i] for i in range(len(A[1]))]
if a == 0:
    print("".join(ANS))
else:
    print("".join(ANS[::-1]))

Submission status: Accepted

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

for _ in range(Q):
  q=input().split()
  if q[0]=="1":
    rev*=-1
  else:
    F,C=int(q[1]),q[2]
    if F==1:
      if rev==1:
        S.appendleft(C)
      else:
        S.append(C)
    else:
      if rev==1:
        S.append(C)
      else:
        S.appendleft(C)

if rev==-1:
  S.reverse()
print("".join(list(S)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
s = input().rstrip('\n')
q = int(input())
s1 = []
s2 = []
k = 0
for i in range(q):
    r = input().rstrip("\n")
    if r == "1":
        k = (k + 1) % 2
    else:
        _, f, c = r.split()
        f = int(f) - 1
        if (k + f) % 2:
            s2.append(c)
        else:
            s1.append(c)

s1.reverse()
ans = s1 + list(s) + s2

if k:
    ans.reverse()
print("".join(ans))

Submission status: Accepted

Solution code:
from collections import deque
s = list(input())
q = int(input())
d = deque()
d.append(0)
now = 1
for i in range(q):
    q1 = list(input())
    if len(q1) == 1:
        now *= -1
    else:
        if q1[2] == "1":
            if now == 1:
                d.appendleft(q1[4])
            else:
                d.append(q1[4])
        else:
            if now == 1:
                d.append(q1[4])
            else:
                d.appendleft(q1[4])
ans = ""
#print(now,d)
while len(d):
    if now == 1:
        a = d.popleft()
    else:
        a = d.pop()
    if a == 0:
        if now == 1:
            for i in range(len(s)):
                ans += s[i]
        else:
            for i in range(len(s)):
                ans += s[-(i+1)]
    else:
        ans += a
print(ans)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
s=input().rstrip()
q=int(input())
count=0
pre=[]
post=[]
for i in range(q):
    l=input().split()
    if len(l)==1:
        count+=1
    else:
        f=int(l[1])
        c=l[2]
        if count%2==0:
            if f==1:
                pre.append(c)
            else:
                post.append(c)
        else:
            if f==1:
                post.append(c)
            else:
                pre.append(c)
if count%2==0:
    pre.reverse()
    for i in pre:
        print(i,end='')
    print(s,end='')
    for i in post:
        print(i,end='')
else:
    post.reverse()
    for i in post:
        print(i,end='')
    n=len(s)
    for i in range(n-1,-1,-1):
        print(s[i],end='')
    for i in pre:
        print(i,end='')

Submission status: Accepted

Solution code:
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement, groupby
from math import sqrt, factorial, log
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappop, heappush, heappushpop
import sys
stdin = sys.stdin
mod = 10**9 + 7

def ns(): return stdin.readline().rstrip()
def ni(): return int(ns())
def na(): return list(map(int, stdin.readline().split()))

s = deque(ns())
q = ni()
now = 1
for i in range(q):
    qu = ns().split()
    if qu[0] == "1":
        now *= -1
    else:
        if qu[1] == "1":
            r = 1
        else:
            r = -1
        if r * now == 1:
            s.appendleft(qu[-1])
        else:
            s.append(qu[-1])
if now == -1:
    s.reverse()
print(*s, sep="")

Submission status: Accepted

Solution code:
from collections import deque

import sys
input = sys.stdin.readline

S = input().strip()

is_front = True # 最初は左向き
queue = deque(S)

Q = int(input())
for _ in range(Q):
    query = input().strip().split()
    if len(query) == 1:
        is_front = not is_front
    else:
        ti, fi, ci = query
        fi = int(fi)
        if is_front:
            if fi == 1:
                queue.appendleft(ci)
            else:
                queue.append(ci)
        else:
            if fi == 1:
                queue.append(ci)
            else:
                queue.appendleft(ci)

ans = "".join(queue)
if not is_front:
    ans = ans[::-1]
print(ans)

Submission status: Accepted

Solution code:
s = input()
q = int(input())
Q = []

for i in range(q):
    Q.append([x for x in input().split()])

bef = ""
aft = ""
flag = True

for i in Q:
    if i[0] == "1":
        flag = not(flag)
    else:
        if i[1] == "1":
            if flag == True:
                bef = i[2]+bef
            else:
                aft = aft+i[2]
        else:
            if flag == True:
                aft = aft+i[2]
            else:
                bef = i[2]+bef

if flag:
    print(bef+s+aft)
else:
    print(aft[::-1]+s[::-1]+bef[::-1])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
s = input()
q_num = int(input())

mae = ""
ushiro = ""
docchi = True

for i in range(q_num):
    query = input()
    if query == '1':
        if docchi:
            docchi = False
        else:
            docchi = True
    else:
        tmp = query.split(' ')
        f = int(tmp[1])
        c = tmp[2]
        if (f == 1 and docchi) or (f == 2 and not docchi):
            mae = c + mae
        else:
            ushiro = ushiro + c

if docchi:
    print(mae + s + ushiro)
else:
    print(''.join(list(reversed(mae + s + ushiro))))

Submission status: Accepted

Solution code:
a = list(raw_input())
b = []
q = input()
for _ in xrange(q):
    line = raw_input().split()
    if line[0] == "1":
        a, b = b, a
    elif line[1] == "1":
        b.append(line[2])
    else:
        a.append(line[2])
print ''.join(b[::-1] + a)

Submission status: Accepted

Solution code:
from sys import stdin
from collections import deque
def main():
    readline=stdin.readline
    S=readline().strip()
    d=deque(S)

    Q=int(readline())
    mode=1
    count=0
    for i in range(Q):
        li=readline().split()
        if li[0]=="1":
            mode+=1
            mode%=2
            count+=1
        else:
            o=li[1]
            c=li[2]
            if mode==1 and o=="1":
                d.appendleft(c)
            elif mode==0 and o=="1":
                d.append(c)
            elif mode==1 and o=="2":
                d.append(c)
            elif mode==0 and o=="2":
                d.appendleft(c)
    res=list(d)
    if count%2==1:
        res=res[::-1]
    print("".join(res))
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
S = input()
Q = int(input())
muki = 1
one = ''
two = ''

for i in range(Q):
    I = input().split()
    if I[0] == '1':
        muki *= -1
    elif I[0] == '2':
        F = int(I[1])
        C = I[2]
        if F==1:
            if muki == 1:
                t = [one, C ]
                one = ''.join(t)
            else:
                t = [two, C ]
                two = ''.join(t)
        elif F==2:
            if muki == 1:
                t = [two, C ]
                two = ''.join(t)
            else:
                t = [one, C ]
                one = ''.join(t)
if muki == 1:
    ANS = [one[::-1],S,two]
    print(''.join(ANS))
else:
    ANS = [two[::-1],S[::-1],one]
    print(''.join(ANS))

Submission status: Accepted

Solution code:
import sys

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

heads = []
tails = []
is_reverse = -1

for i in range(q):
    query = sys.stdin.readline().strip()

    if query[0] == '1':
        is_reverse *= -1
    else:
        t, f, c = query.split()
        if f == '1':  # to current head
            if is_reverse == 1:
                tails.append(c)
            else:
                heads.append(c)
        else:  # to current tail
            if is_reverse == 1:
                heads.append(c)
            else:
                tails.append(c)

if is_reverse == 1:
    print(''.join(tails[::-1]) + s[::-1] + ''.join(heads))
else:
    print(''.join(heads[::-1]) + s + ''.join(tails))

Submission status: Accepted

Solution code:
# 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_map_as_int(H):
    '''
    #→1,.→0として読み込む
    '''
    ret = []
    for _ in range(H):
        ret.append([1 if s == '#' else 0 for s in read()[:-1]])
    return ret


from collections import deque
S = deque(read()[:-1])
Q = read_a_int()


is_flip = 0  # 0は反転してない
for _ in range(Q):
    q = input().split()
    if len(q) == 1:
        is_flip = 1 - is_flip
    else:
        _, f, c = q
        f = int(f)
        if is_flip:
            if f == 1:
                S.append(c)
            else:
                S.appendleft(c)
        else:  # flipしてないときは通常の処理
            if f == 1:
                S.appendleft(c)
            else:
                S.append(c)

if is_flip:
    print(''.join(S)[::-1])
else:
    print(''.join(S))

Submission status: Accepted

Solution code:
s=list(input())
n=int(input())
from collections import deque
d=deque(s)
cnt=0
for i in range(n):
    a=list(input().split())
    if len(a)==1:
        cnt+=1
    else:
        if cnt%2==0:
            if a[1]=="1":
                d.appendleft(a[2])
            else:
                d.append(a[2])
        else:
            if a[1]=="2":
                d.appendleft(a[2])
            else:
                d.append(a[2])
if cnt%2==1:
    d=list(d)
    d=d[::-1]
    print("".join(d))
else:
    print("".join(d))

Submission status: Accepted

Solution code:
from collections import deque
X = input()
S = deque()
for e in X:
    S.append(e)
Q = int(input())
flip = 0
for i in range(Q):
    query = input()
    if query == str(1):
        flip += 1
    else:
        f = int(query[2])
        c = query[-1]
        if f == 1:
            if flip%2 == 1:
                S.append(c)
            else:
                S.appendleft(c)
        else:
            if flip%2 == 1:
                S.appendleft(c)
            else:
                S.append(c)
S = "".join(S)
if flip%2 == 1:
    print(S[::-1])
else:
    print(S)

Submission status: Accepted

Solution code:
from collections import deque
s = deque(input())
q = int(input())
rev= 0
for i in range(q):
    x = list(input().split())
    if x [0] == '1':
        rev += 1
    else:
        if x[1] == '1':
            if rev % 2 == 0:
                s.appendleft(x[2])
            else:
                s.append(x[2])
        else:
            if rev % 2 == 0:
                s.append(x[2])
            else:
                s.appendleft(x[2])
if rev % 2 == 1:
    s.reverse()
print("".join(s))

Submission status: Accepted

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

S = str(input())
q = int(input())

p = ''
s = ''
cur = 0
for i in range(q):
    query = input().split()
    #print(query)
    if len(query) == 1:
        if cur == 0:
            cur = 1
        else:
            cur = 0
    else:
        t, f, c = query
        if f == '1':
            if cur == 0:
                p = c + p
            else:
                s = s + c
        else:
            if cur == 0:
                s  = s + c
            else:
                p = c + p
ans = p+S+s
if cur == 1:
    ans = ''.join(list(reversed(ans)))
print(ans)

Submission status: Accepted

Solution code:
S=[ord(c) for c in input()]
l,r=2*10**5-1,2*10**5+len(S)
S=[-1]*(2*10**5)+S+[-1]*(2*10**5)
x=0
Q=int(input())
qs=[input() for i in range(Q)]
for q in qs:
    if q=='1':
        x^=1
    else:
        _,f,c=q.split()
        if x==0 and int(f)==1 or x==1 and int(f)==2:
            S[l]=ord(c)
            l-=1
        else:
            S[r]=ord(c)
            r+=1
print(''.join([chr(c) for c in S[l+1:r]])[::(-1 if x else 1)])

Submission status: Accepted

Solution code:


def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
from collections import deque


def main():
    mod=10**9+7
    S=deque(input())
    Q=I()
    dir=0#0で手前につける
    
    for _ in range(Q):
        q=list(input().split())
        if q[0]=="1":
            dir+=1
            dir%=2
        else:
            dir2=dir
            if q[1]=="2":
                dir2+=1
                dir2%=2
            if dir2==0:
                S.appendleft(q[2])
            else:
                S.append(q[2])
            
    ans=list(S)
    
    if dir==1:
        ans=ans[::-1]
        
    print(''.join(map(str, ans)))
        

main()

Submission status: Accepted

Solution code:
import sys
range = xrange
input = raw_input

S = input()
start = []
end = []
par = 1

q = int(input())
for _ in range(q):
    quer = input()
    if quer == '1':
        par ^= 1
    else:
        _, f, c = quer.split()
        f = int(f) - 1
        if par ^ f:
            start.append(c)
        else:
            end.append(c)

T = ''.join([''.join(reversed(start)), S, ''.join(end)])

if par:
    print T
else:
    print T[::-1]