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: Time Limit Exceeded

Solution code:
s = input()
q = int(input())
for i in range(q):
    que = list(input().split())
    if que[0] == "1":
        s = s[::-1]
    else:
        if que[1]=="1":
            s = que[2]+s
        else:
            s = s+que[2]
print(s)

Submission status: Time Limit Exceeded

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

for i in Query:
    if int(i[0]) == 1:
        S = S[::-1]
    elif int(i[0]) == 2:
        if int(i[1]) == 1:
            S = i[2] + S
        elif int(i[1]) == 2:
            S = S + i[2]


print(S)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


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


def S(): return input()


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


def MS(): return map(str, input().split())


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


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


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


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def main():
    st = S()
    Q = I()
    queries = []
    # print(st[0])
    s = [st[i] for i in range(len(st))]

    for i in range(Q):
        queries.append(list(MS()))

    op = True

    for i in range(Q):
        query = queries[i]
        if len(query) == 1:
            op = not op
        else:
            if (query[1] == '1' and op is True) or (query[1] == '2' and op is False):
                s.insert(0, query[2])
            elif (query[1] == '1' and op is False) or (query[1] == '2' and op is True):
                s.append(query[2])
            else:
                exit(-1)
                return

    if op is True:
        print(''.join(s))
    else:
        print(''.join(s[::-1]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
s=list(str(input()))
q=int(input())
for i in range(q):
    l=list(map(str,input().split()))
    if l[0]=="1":
        s.reverse()
    else:
        if l[1]=="1":
            s=[l[2]]+s
        else:
            s=s+[l[2]]
print("".join(s))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
S=deque(input())
Q=int(input())
for _ in range(Q):
    target = input()
    if target == '1':
        S.reverse()
    else:
        a,b,c=target.split()
        if b=='1':
            S.appendleft(c)
        else:
            S.append(c)
print(''.join(list(S)))

Submission status: Time Limit Exceeded

Solution code:
s=list(input())
q=int(input())
rev=1
for qi in range(q):
	a= input()
	if len(a)==1:
		rev*=-1
	else:
		a=a.split(' ')
		if (a[1]=='1' and rev==1) or (a[1]=='2' and rev==-1):
			s.insert(0,a[2])
		else:
			s.append(a[2])
if rev==-1:
	s.reverse()
print(''.join(i for i in s))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
S = list(input())
Q = int(input())

is_reversed = False
for _ in range(Q):
    token = input().split(' ')
    if len(token) == 1:
        is_reversed = ~is_reversed

    else:
        _, f, c = token
        f = int(f)
        if (f == 1 and is_reversed) or (f == 2 and not is_reversed):
            S.append(c)

        else:
        # elif (f == 1 and not is_reversed) or (f == 2 and is_reversed):
            S.insert(0, c)

if is_reversed:
    S.reverse()
    print(''.join(S))

else:
    print(''.join(S))

Submission status: Time Limit Exceeded

Solution code:
# D - String Formation

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

for _ in range(Q):
    q = [str(x) for x in input().split()]
    if q[0] == '1':
        S = ''.join(list(reversed(S)))
    elif q[1]=='1':
        S = q[2]+S
    else:
        S = S+q[2]

print(S)

Submission status: Time Limit Exceeded

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

def solve():
    S = input()
    Q = int(input())

    is_reverse = False # 反転中か？

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

    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            S = S[::-1]
        else:
            t, f, c = query
            if f == "1":
                S = c + S
            else:
                S = S + c

    print(S)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
for i in range(Q):
    query = input().split()
    if int(query[0]) == 1:
        S = S[::-1]
    elif int(query[0]) == 2:
        if int(query[1]) == 1:
            S = query[2] + S
        elif int(query[1]) == 2:
            S = S +query[2]
print(S)

Submission status: Time Limit Exceeded

Solution code:
s = input()
Q = int(input())
for _ in range(Q):
  q = input()
  if (q[0] == "1"):
    s = s[::-1]
  else:
    if (q[2] == "1"):
      s = q[4] + s
    else:
      s = s + q[4]
print(s)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
    S = deque(input())
    Q = int(input())
    for _ in range(Q):
        query = input().split()
        if query[0] == "1":
            S.reverse()
            continue
        if query[1] == "1":
            S.appendleft(query[2])
        else:
            S.append(query[2])
    print("".join(list(S)))
        
if __name__ == "__main__":
    # print(timeit.timeit(lambda: main(), number=1))
    main()

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
judge = False
for _ in range(Q):
  l = list(input().split())
  if int(l[0])==1:
    if judge:
      judge = False
    else:
      judge = True
      
  elif int(l[0])==2:
    f,c = int(l[1]),l[2]
    if judge:
      if f==1:
        f=2
      elif f==2:
        f=1
    if f==1:
      S=c+S
    elif f==2:
      S=S+c
      
if judge:
  S=S[::-1]
print(S)

Submission status: Time Limit Exceeded

Solution code:
def main():

    S = input()
    Q = int(input())
    count = 0
    A = ""
    B = ""
    for _ in range(Q):
        U = input()
        if len(U) == 1:
            count += 1
        else:
            _, F, C = U.split()
            F = int(F)
            if F == 1:
                if count % 2 == 0:
                    A += C
                else:
                    B += C
            else:
                if count % 2 == 0:
                    B += C
                else:
                    A += C

    if count % 2 == 0:
        return A[::-1] + S + B
    else:
        return B[::-1] + S[::-1] + A

if __name__ == '__main__':
    print(main())

Submission status: Time Limit Exceeded

Solution code:
s = input()
n = int(input())
query = []

for i in range(n):
    query.append(list(input().split()))

# print(query)

for i in range(n):
    # Reverse
    if query[i][0] == '1':
        s = s[::-1]
    # Add
    else:
        # To Head
        if query[i][1] == '1':
            s = query[i][2] + s

        # To Tail
        else:
            s += query[i][2]

print(s)

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
query = []
for i in range(Q):
    query.append(list(map(str, input().split())))


def start(S, x, flg):
    if flg == True:
        S = x + S
    else:
        S = S + x
    return S


def end(S, x, flg):
    if flg == True:
        S = S + x
    else:
        S = x + S
    return S


flg = True
for q in query:
    if len(q) == 1:
        flg = not flg
    else:
        if int(q[1]) == 1:
            S = start(S, q[2], flg)
        else:
            S = end(S, q[2], flg)
else:
    if flg == True:
        print(S)
    else:
        print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
s=input()
q=int(input())
for _ in range(q):
	k=input()
	if k == "1":
		s = s[::-1]
	else:
		if k[2] == "1":
			s = k[4:]+s
		if k[2] == "2":
			s = s+k[4:]
print(s)

Submission status: Time Limit Exceeded

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

def solve(S, query):
    flag = False
    S = list(S)
    for q in query:
        command = q.split()
        T = int(command[0])
        if T == 1:
            flag = not flag
        elif T == 2:
            F = int(command[1])
            C = command[2]
            if (not flag and F == 1) or (flag and F == 2):
                S.insert(0, C)
            else:
                S.append(C)
    if flag:
        S.reverse()
    return ''.join(S)


def main():
    S = input()
    Q = int(input())
    query = [input() for n in range(Q)]
    print(solve(S, query))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
S=input()
q=int(input())
for i in range(q):
    IN=input()
    if IN=="1":
        S=S[::-1]
    else:
        t,f,c=IN.split()
        if f=="1":
            S=c+S
        elif f=="2":
            S=S+c
print(S)

Submission status: Time Limit Exceeded

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

Query = [list(input()) for i in range(Q)]

for i in range(Q):
    if Query[i][0] == "1":
        S.reverse()
    else:
        if Query[i][2] == "1":
            S.insert(0, Query[i][4])
        else:
            S.append(Query[i][4])

print("".join(S))

Submission status: Time Limit Exceeded

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

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

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

def main():
  s=S()
  f=True
  q=I()

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

  if f:
    return s
  ans=list(s)
  ans.reverse()
  return ''.join(ans)

# main()
print(main())

Submission status: Time Limit Exceeded

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

for i in range(q):
    s1=input()
    if len(s1)==1:
        hanten+=1
    else:
        a,f,c=s1.split()
        f=int(f)
        if (f+hanten)%2==0:
            s = s + c
        else:
            s = c + s     

if hanten%2==0:
    print(s)
else:
    print(s[::-1])

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
for _ in range(Q):
    command = input()
    try:
        a, b, char = command.split()
        if b == '1': S = char + S
        else: S = S + char
    except: S = S[::-1]
print(S)

Submission status: Time Limit Exceeded

Solution code:
def f(t):
    return t

s=input()
q=int(input())
queri=[]
rv=0
for i in range(q):
    tmp=list(map(f,input().split()))
    queri.append(tmp)
    if tmp==["1"]:
        rv+=1
rv=rv%2
if rv==1: s=s[::-1]

for i in range(q):
    if queri[i][0]=="2":
        rvt=(rv+int(queri[i][1]))%2
        if rvt==1: s=queri[i][2]+s
        else: s=s+queri[i][2]

    else: rv=(rv+1)%2

print(s)

Submission status: Time Limit Exceeded

Solution code:

S = list(input())
Q = int(input())
l = []
for i in range(Q):
  l.append(list(input().split()))
    
for i in range(Q):
    if l[i][0] == "1":
        S.reverse()
    else:
        if l[i][1] == "1":
            S = list(l[i][2]) + S
            
        else:
            S = S + list(l[i][2])
            
print("".join(S))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
S=input()
Q=int(input())
que=[]
for i in range(Q):
    q=input().split()
    que.append(q)
#print(que)
tmp=0
for i in range(Q):
    if que[i][0]=='1':
        tmp=1-tmp
    if que[i][0]=='2':
        if que[i][1]=='1':
            if tmp==0:
                S=que[i][2]+S
            else:
                S=S+que[i][2]
        else:
            if tmp==0:
                S=S+que[i][2]
            else:
                S=que[i][2]+S
#print(tmp)
ans=""
if tmp==1:
    for i in range(len(S)):
        ans=S[i]+ans
    print(ans)
    exit()

print(S)

Submission status: Time Limit Exceeded

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

sei_or_gyaku = 1
mae = ''
ato = ''

for i in range(q):
    sirei = input()
    if len(sirei) == 1:
        ti = int(sirei)
        sei_or_gyaku *= -1
    else:
        ti, fi, ci = map(str, sirei.split())
        ti, fi = int(ti), int(fi)
        if fi == 1:
            if sei_or_gyaku == 1:
                mae = ci + mae
            else:
                ato = ato + ci
        else:
            if sei_or_gyaku == 1:
                ato = ato + ci
            else:
                mae = ci + mae

ans = mae + s + ato
if sei_or_gyaku == 1:
    print(ans)
else:
    print(ans[::-1])

Submission status: Time Limit Exceeded

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

for i in range(q):
    query = input()
    if query[0] == '1':
        s = list(s)
        s.reverse()
        s = ''.join(s)
    else:
        if query[2] == '1':
            s = query[4]+s
        else:
            s = s+query[4]
print(s)

Submission status: Time Limit Exceeded

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

for i in range(Q):
    que = list(input().split())
    if que[0] == str(1):
        S = S[::-1]
    else:
        if int(que[1]) == 1:
            S.insert(0, que[2])
        else:
            S.append(que[2])

print(''.join(S))

Submission status: Time Limit Exceeded

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

t = 1
for i in range(Q):
    A = input()
    if A=="1":
        t*=-1
    else:
        AL = list(A.split())
        if AL[1]=="1":
            if t==1:
                S = AL[2]+S
            else:
                S = S+AL[2]
        elif AL[1]=="2":
            if t==1:
                S = S+AL[2]
            else:
                S = AL[2]+S

if t==-1:
    print(S[::-1])
else:
    print(S)

Submission status: Time Limit Exceeded

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

for i in range(q):
    if ls[i][0] == '1':
        s = s[::-1]
    elif ls[i][0] == '2':
        if ls[i][1] == '1':
            s = ls[i][2] + s
        elif ls[i][1] == '2':
            s = s + ls[i][2]
    
print(s)

Submission status: Time Limit Exceeded

Solution code:
s = input()
q = int(input())
for i in range(q):
    query = input().split()
    if query[0] == '1':
        s = s[::-1]
    elif query[1] == '1':
        s = query[2] + s
    else:
        s = s + query[2]
print(s)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
S=input()
S_list=deque()
for k in range(len(S)):
    S_list.append(S[k])
Q=int(input())
kouho=deque()
for i in range(Q):
    kari=input().split()
    kouho.append(kari)
for j in range(len(kouho)):
    if kouho[j][0]=="1":
        S_list.reverse()
    else:
        if kouho[j][1]=="1":
            S_list.appendleft(kouho[j][2])
        else:
            S_list.append(kouho[j][2])
print(*S_list,sep="")

Submission status: Time Limit Exceeded

Solution code:
S = list(input())
Q = int(input())
inversion_flag = False
for _ in range(Q):
    query_list = list(input().split())
    if query_list[0] == "1":
        inversion_flag = not inversion_flag
        continue
    C = query_list[2]
    if query_list[1] == "2":
        if inversion_flag:
            S.insert(0, C)
        else:
            S.append(C)
    else:
        if inversion_flag:
            S.append(C)
        else:
            S.insert(0, C)

if inversion_flag:
    print(*S[::-1], sep="")
else:
    print(*S, sep="")

Submission status: Time Limit Exceeded

Solution code:
s = input()
r = 0

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

    if a[0] == '1':
        r = 1 - r
    else:
        if (a[1] == '1' and r == 0) or (a[1] == '2' and r == 1):
            s = a[2] + s
        else:
            s = s + a[2]

print(s if r == 0 else s[::-1])

Submission status: Time Limit Exceeded

Solution code:
def main():
    S = raw_input()
    Q = int(raw_input())

    is_reversed = False

    for _ in range(Q):
        query = raw_input().split()
        if query[0] == "1":
            is_reversed = not is_reversed
        elif query[0] == "2":
            F = int(query[1])
            C = query[2]
            if F == 1:
                if not is_reversed:
                    S = C + S
                else:
                    S = S + C
            elif F == 2:
                if not is_reversed:
                    S = S + C
                else:
                    S = C + S


    if not is_reversed:
        ans =  S
    else:
        ans = S[::-1]
    print ans

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
S = list(input())
Q = int(input())
lst = []

for i in range(Q):
    tmp = list(input().split())
    lst.append(tmp)

for i in range(Q):
    if int(lst[i][0]) == 1:
        S.reverse()
    if int(lst[i][0]) == 2:
        if int(lst[i][1]) == 1:
            S.insert(0,lst[i][2])
        else:
            S.append(lst[i][2])

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

Submission status: Time Limit Exceeded

Solution code:
s = input().strip()
q = int(input())
l, r = "", ""
rev = 0
for i in range(q):
    a = input().split()
    t = int(a[0])
    if t == 1:
        rev += 1
    else:
        f = int(a[1])
        c = a[2]
        if f == 1:
            if rev % 2 == 0:
                l = c+l
            else:
                r = r+c
        else:
            if rev % 2 == 0:
                r = r+c
            else:
                l = c+l

if rev % 2 == 0:
    print(l+s+r)
else:
    print(r[::-1]+s[::-1]+l[::-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	S = input()
	S = S[:-1]
	Q = inputInt()

	save = []

	flg = True
	for _ in range(Q):
		inp = input()
		inp = inp[:-1]
		inpt = inp.split()

		if len(inpt) == 1:
			if flg == True:
				flg = False
			else:
				flg = True
		else:
			oder = inpt[1]
			if oder == "1":
				if flg == True:
					S = inpt[2] + S
				else:
					S = S + inpt[2]
			else:
				if flg == True:
					S = S + inpt[2]
				else:
					S = inpt[2] + S
	if flg == True:
		print(S)
	else:
		print(S[::-1])



#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# special thanks :
#  https://nagiss.hateblo.jp/entry/2019/07/01/185421
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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

reverse = False
count = 0
for i in range(q):
    qu = input()
    if qu[0] == "1":
        count += 1
        if reverse:
            reverse = False
        else:
            reverse = True
    else:
        _, f, c = qu.split()
        if reverse:
            if f == "1":
                s = s + c
            else:
                s = c + s
        else:
            if f == "1":
                s = c + s
            else:
                s = s + c

if count % 2:
    print(s[::-1])
else:
    print(s)

Submission status: Time Limit Exceeded

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

for i in range(Q):
    q = input()
    if q == '1':
        S = S[::-1]
        continue
    t,f,c = q.split()
    if f == '1':
        S = c + S
    else:
        S = S + c

print(S)

Submission status: Time Limit Exceeded

Solution code:
"""
// Author : snape_here - Susanta Mukherjee
     
"""
 
from __future__ import division, print_function
 
import os,sys
from io import BytesIO, IOBase
 
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
 
 
def ii(): return int(input())
def si(): return input()
def mi(): return map(str,input().split())
def li(): return list(mi())
 
 
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x
    
 
def read():
    sys.stdin = open('input.txt', 'r')  
    sys.stdout = open('output.txt', 'w') 
 
 
import math

mod=1000000007 

def main():

    s=si()
    for i in range(ii()):
        a=li()
        if len(a)==1:
            s=s[::-1]
        else:
            if a[1]=='1':
                s=a[2]+s 
            else:
                s+=a[2]
    print(s)

# region fastio#
 
BUFSIZE = 8192
 
 
class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
 
 
def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
 
 
if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
 
input = lambda: sys.stdin.readline().rstrip("\r\n")
 
# endregion
 
 
if __name__ == "__main__":
    #read()
    main() 
#Comment read()

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
for i in range(Q):
    q = input()
    if q[0]=='1':
        S = S[::-1]
    if q[0]=='2':
        n, f= map(int, q[:-1].split())
        c = q[-1]
        if f==1:
            S = c + S
        if f==2:
            S = S + c
print(S)

Submission status: Time Limit Exceeded

Solution code:
s = str(input())
n = int(input())
 
for i in range(n):
    q = list(map(str,input().split()))
    if len(q) == 1 and q[0] == "1":
        s = s[::-1]
    elif q[1] == "1":
        s = q[2] + s
    elif q[1] == "2":
        s = s + q[2]
 
 
print(s)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
# coding: utf-8
from fractions import gcd 
from functools import reduce
import sys
sys.setrecursionlimit(200000000)
from inspect import currentframe


# my functions here!
#標準エラー出力
def printargs2err(*args):
    names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???')+' : '+repr(arg) for arg in args),file=sys.stderr)
def debug(*args):
    print(*args,file=sys.stderr)

def printglobals():
    for (symbol, value) in globals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
def printlocals():
    for (symbol, value) in locals().items():
        print('symbol="%s"、value=%s' % (symbol, value),file=sys.stderr)
#入力（後でいじる）
def pin(type=int):
    return map(type,input().split())
     
#input
from collections import deque
def resolve():
    S=deque(input())
    Q,=pin()
    ans=""
    turn=0
    for i in range(Q):
        q=input().split()
        if q[0]=="1":turn=(turn+1)%2
        else:
            f=int(q[1])%2
            if f!=turn:
                S.appendleft(q[2])
            else:
                S.append(q[2])
    if turn==1:S.reverse()
    for s in S:
        ans+=s
    print(ans)
    #print([["NA","YYMM"],["MMYY","AMBIGUOUS"]][cMMYY][cYYMM])
#if __name__=="__main__":resolve()

"""
#printデバッグ消した？
#前の問題の結果見てないのに次の問題に行くの？
"""
"""
お前カッコ閉じるの忘れてるだろ
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """a
4
2 1 p
1
2 2 c
1"""
        output = """cpa"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """a
6
2 2 a
2 1 b
1
2 2 c
1
1"""
        output = """aabc"""
        self.assertIO(input, output)
    def test_入力例_3(self):
        input = """y
1
2 1 x"""
        output = """xy"""
        self.assertIO(input, output)

if __name__=="__main__":resolve()