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 = list(input().strip())
q = int(input().strip())
queries = []
one_count = 0
one_counts = []
for i in range(q):
    inp = input().split()
    queries.append(inp)
    if inp[0] == "1":
        one_count += 1
    one_counts.append(one_count)
one_counts = list(map(lambda x: (one_count - x), one_counts))
if one_count % 2 == 1:
    s = s[::-1]
pre = []
suf = []
for i in range(q):
    if queries[i][0] == "1":
        continue
    elif queries[i][0] == "2":
        if queries[i][1] == "1":
            if one_counts[i] % 2 == 0:
                pre.insert(0, queries[i][2])
            else:
                suf.append(queries[i][2])
        elif queries[i][1] == "2":
            if one_counts[i] % 2 == 0:
                suf.append(queries[i][2])
            else:
                pre.insert(0, queries[i][2])
print("".join(pre + s + suf))

Submission status: Time Limit Exceeded

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


s = input().rstrip()
q = int(input())

for i in range(q):
    query = list(input().split())
    if len(query) == 1:
        s = ''.join(list(reversed(s)))
    elif query[1] == '1':
        s = query[2] + s
    elif query[1] == '2':
        s = s + query[2]
        
print(s)

Submission status: Time Limit Exceeded

Solution code:
s=input()
q=int(input())
re=False
for i in range(0,q):
    Q=input()
    if int(Q[0])==1:
        re=not re
        continue
    if int(Q[0])==2:
        if (int(Q[2])==1 and (not re)) or (int(Q[2])==2 and re):
            s=Q[4]+s
            continue
        if (int(Q[2])==1 and re) or (int(Q[2])==2 and (not re)):
            s=s+Q[4]
if re==True:
    s=s[::-1]
print(s)

Submission status: Time Limit Exceeded

Solution code:
def main():
  s=input()
  q=int(input())
  turn = 2
  tmp=[]
  for i in s:
      tmp.append(i)
  for _ in [0]*q:
      query = input()
      try:
          t = int(query)
          turn = 3 - turn
      except ValueError:
          t,f,c = map(str,query.split())
          if (int(f) + turn)% 2  == 0:
              tmp.append(c)
          else:
              tmp = [c] + tmp
  if turn == 2:
      print("".join(tmp))
  else:
      print("".join(tmp[::-1]))
main()

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=[input().split() for i in range(Q)]
"""for i in range(Q):
    kari=input().split()
    kouho.append(kari)"""
hanten=[]
count=0
flaag=["sonomama","hantai"]

for j in range(Q):
    flag=flaag[count%2]
    if kouho[j][0]=="1":
        count+=1
    else:
        if flag=="sonomama":
            if kouho[j][1]=="1":
                S_list.appendleft(kouho[j][2])
            else:
                S_list.append(kouho[j][2])
        else:
            if kouho[j][1]!="1":
                S_list.appendleft(kouho[j][2])
            else:
                S_list.append(kouho[j][2])
for k in range(count):
    S_list.reverse()
print(*S_list,sep="")

Submission status: Time Limit Exceeded

Solution code:
texts = str(input())
Q = int(input())


reverse = False
start_text = ''
end_text = ''
input_texts = []
for _ in range(Q):
    input_texts.append(list(input().split()))

for input_text in input_texts:
    if len(input_text) == 1:
        if reverse:
            reverse = False
        else:
            reverse = True
    else:
        if input_text[1] == '1':  # 先頭に
            if reverse:
                end_text += str(input_text[2])
            else:
                start_text = str(input_text[2]) + start_text
        else:  # 末尾に
            if reverse:
                start_text = str(input_text[2]) + start_text
            else:
                end_text += str(input_text[2])

if reverse:
    text = ''.join(texts)
    text = list(start_text + text + end_text)
    text.reverse()
    print("".join(text))
else:
    text = ''.join(texts)
    text = start_text + text + end_text
    print(text)

Submission status: Time Limit Exceeded

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

def t1(bs):
    ss = bs[-1]
    for i in range(len(bs) - 2, -1, -1):
        ss += bs[i]
    return ss

def t2(bs, fi, ci):
    if fi == "1":
        return ci + bs
    elif fi == "2":
        return bs + ci

for i in range(q):
    o = input()
    if o[0] == "1":
        s = t1(s)
    elif o[0] == "2":
        s = t2(s, o[2], o[4])
print(s)

Submission status: Time Limit Exceeded

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

Qu =[]
for i in range(Q):
    Qu.append(list(map(str,input().split())))
cnt = 0
for i in range(Q):
    if Qu[i][0] == '1':
        cnt += 1 #奇数の時は逆、偶数の時は正順
        #S = S[::-1]
    elif Qu[i][0] == '2':
        if cnt%2 == 0:
            if Qu[i][1] == '1':
                S = Qu[i][2] + S
            elif Qu[i][1] == '2':
                S = S + Qu[i][2]
        elif cnt%2 != 0:
            if Qu[i][1] == '2':
                S = Qu[i][2] + S
            elif Qu[i][1] == '1':
                S = S + Qu[i][2]
if cnt % 2 ==0:
    print(S)
else:
    print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
s=deque(list(input()))
q=int(input())
direction=0 #0:順 1:逆

for i in range(q):
    query=list(input().split())
    i=int(query[0])
    if i==1:
        direction=direction^1
    elif i==2:
        f,c=int(query[1]),query[2]
        if f==1 and direction==0:
            s.appendleft(c)
        elif f==1 and direction==1:
            s.append(c)
        elif f==2 and direction==0:
            s.append(c)
        elif f==2 and direction==1:
            s.appendleft(c)

if direction==0:
    print(*s,sep='')
else:
    x=[]
    for i in range(len(s)):
        x.append(s[-1-i])
    print(*x,sep='')

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

R=True
ans=deque(list(s))
count=0

for i in range(q):
    l=list(map(str,input().split()))
    if int(l[0])==1:
        if R:
            R=False
        else:
            R=True
        count+=1
    else:
        f,c=int(l[1]),l[2]
        if f==1 and R:
            ans.appendleft(c)
        elif f==2 and R:
            ans.append(c)
        elif f==1 and (not R):
            ans.append(c)
        elif f==2 and (not R):
            ans.appendleft(c)

string=""
if count%2==0:
    for i in range(len(ans)):
        string+=ans[i]
else:
    for i in range(len(ans))[::-1]:
        string+=ans[i]
print(string)

Submission status: Time Limit Exceeded

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

flg = 1
for i in range(q):
    t = input()
    if t == "1":
        if flg:
            flg = 0
        else:
            flg = 1
    elif t[0] == "2":
        f = t[2]
        if f == "1":
            c = t[4]
            if flg:
                s = c + s
            else:
                s += c
        elif f == "2":
            c = t[4]
            if flg:
                s += c
            else:
                s = c + s

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

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
S = input()
x = S
y =str()   
N = int(input())
Q =  [list(map(str, stdin.readline().split())) for _ in range(N)]
flag = True
for i in range(N):
    if Q[i][0]=="1":
        flag = not(flag)                
    else: 
        if (Q[i][1] == "2") == (flag == True):
            x += Q[i][2]#先頭
        else :
            y += Q[i][2]
M = "".join([y[::-1],x])
if flag == True:
    print(M)
else:
    print(M[::-1])

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce

S = input()
count = int(input())

reverse_flag = False

idx = 1
while idx <= count:
  idx += 1
  process = input().split()
  if process[0] == '1':
    reverse_flag = not reverse_flag
  else:
    if process[1] == '1':
      S = S + process[2] if reverse_flag else process[2] + S
    else:
      S = process[2] + S if reverse_flag else S + process[2]

if reverse_flag:
  print(S[::-1])
else:
  print(S)

Submission status: Time Limit Exceeded

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

d = deque()
d.extend(S)
for i in range(1, Q+1):
    query = input()
    if len(query) == 1:
        d.reverse()
    else:
        n, F, C = query.split()
        if F == '1':
            d.appendleft(C)
        else:
            d.append(C)

l = list(d)
S = ''.join(l)
print(S)

Submission status: Time Limit Exceeded

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

  for _ in [0]*q:
      query = input()
      try:
          t = int(query)
          turn = 3 - turn
      except ValueError:
          t,f,c = map(str,query.split())
          if (int(f) + turn)% 2  == 0:
              s = s + c
          else:
              s = c + s
  if turn == 2:
      print(s)
  else:
      print(s[::-1])
main()

Submission status: Time Limit Exceeded

Solution code:
S = [i for i in input()]
Q = int(input())
rev_num = 0
for i in range(Q):
  query = [i for i in map(str,input().split())]
  if query[0]=='1':
    rev_num += 1
  else:
    if query[1]=='1':
      if rev_num%2==1:
        S.append(query[2])
      else:
        S.insert(0,query[2])
    else:
      if rev_num%2==1:
        S.insert(0,query[2])
      else:
        S.append(query[2])
        
if rev_num%2:
  S.reverse()
print(''.join(S))

Submission status: Time Limit Exceeded

Solution code:
S = [input()]
Q = int(input())
querys = [input() for _ in range(Q)]
is_reverse = False

for q in querys:
    query = q.split()
    if len(query) == 1:
        is_reverse = not is_reverse
        continue
    _, f, c = query
    if is_reverse:
        
        if f == "1":
            S = S + [c]
        elif f == "2":
            S = [c] + S
    else:
        if f == "1":
            S = [c] + S
        elif f == "2":
            S = S + [c]
if is_reverse:
    print("".join(S)[::-1])
else:
    print("".join(S))

Submission status: Time Limit Exceeded

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

key = 0

for i in range(Q):
    Query = input().split()
    if Query[0] == '1':
        key += 1
    else:
        if (key+int(Query[1])) % 2 == 1:
            S = Query[2] + S
        else:
            S = S + Query[2]

if key % 2 == 1:
    S = S[::-1]

print(S)

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
T = [input() for i in range(Q)]

count = True

for i in range(Q):
  t = T[i]
  if(int(t[0]) == 1):
    count = not count
  else:
    if(int(t[2]) == 1):
      if(count):
        S = "".join([t[4], S])
      else:
        S = "".join([S, t[4]])
    else:
      if(count):
        S = "".join([S, t[4]])
      else:
        S = "".join([t[4], S])

if(count):
  print(S)
else:
  print(S[::-1])

Submission status: Time Limit Exceeded

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

reversing = False

for i in range(Q):
    query = list(input().split())
    if int(query[0]) == 1:
        reversing = not reversing
    else:
        if int(query[1]) == 1:
            if not reversing:
                S = query[2] + S
            else:
                S += query[2]
        else:
            if reversing:
                S = query[2] + S
            else:
                S += query[2]

print(S) if not reversing else print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
S=input()
Q=int(input())
cnt=True
for i in range(Q):
    query_list=input().split()
    if query_list[0] == "1":
        cnt=(cnt==False)
    else:
        if cnt:
            if query_list[1] == "1":
                S=query_list[2]+S
            else:
                S+=query_list[2]
        else:
            if query_list[1] == "1":
                S+=query_list[2]
            else:
                S=query_list[2]+S
if cnt:
    print(S)
else:
    print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
s=deque(list(input()))
q=int(input())
direction=0 #0:順 1:逆

for i in range(q):
    query=list(input().split())
    if query[0]=='1':
        direction=direction^1
    elif query[0]=='2':
        if query[1]=='1' and direction==0:
            s.appendleft(query[2])
        elif query[1]=='1' and direction==1:
            s.append(query[2])
        elif query[1]=='2' and direction==0:
            s.append(query[2])
        elif query[1]=='2' and direction==1:
            s.appendleft(query[2])

if direction==0:
    print(*s,sep='')
else:
    x=[]
    for i in range(len(s)):
        x.append(s[-1-i])
    print(*x,sep='')

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

S = input()
Q = int(input())
reverse_cnt = 0
index = []
s = deque([])

for i in range(Q):
    query = input().split()
    if query[0] == "1":
        reverse_cnt += 1
        index = list(np.array(index) * -1)
    else:
        s.append(query[2])
        if query[1] == "1":
            index.append(-1)
        else:
            index.append(1)

if reverse_cnt % 2 != 0:
    S = S[::-1]

insert = ""
add = ""

for i in index:
    if i == 1:
        add += s.popleft()
    elif i == -1:
        insert += s.popleft()

print(insert[::-1] + S + add)

Submission status: Time Limit Exceeded

Solution code:
S = input()
Q = int(input())
T = [input() for i in range(Q)]

count = True

for i in range(Q):
  t = T[i]
  if(int(t[0]) == 1):
    count = not count
  else:
    if(int(t[2]) == 1):
      if(count):
        list = [t[4], S]
        S = "".join(list)
      else:
        list = [S, t[4]]
        S = "".join(list)
    else:
      if(count):
        list = [S, t[4]]
        S = "".join(list)
      else:
        list = [t[4], S]
        S = "".join(list)

if(count):
  print(S)
else:
  print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
#!/bin/bash
''':'
docker run --rm -it -v $(cd $(dirname $0) && pwd):/vo:ro pypy:3-2.4.0 \
   /bin/bash -c "pypy3 /vo/$(basename $0) < /vo/g.inp"
exit $?
'''
import sys
from collections import deque


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


def _sa(): return sys.stdin.readline().strip().split()


def _i(): return int(sys.stdin.readline().strip())


def main():
    s = deque([c for c in _s()])
    q = _i()
    flip = 0
    for _ in range(q):
        tmp = _sa()
        op = int(tmp[0])
        if op == 1:
            flip ^= 1
        else:
            loc = int(tmp[1]) - 1
            c = tmp[2]
            if flip ^ loc:
                s.append(c)
            else:
                s.appendleft(c)

    ans = ""
    n = len(s)
    for _ in range(n):
        if flip == 0:
            ans += s.popleft()
        else:
            ans += s.pop()
    return ans


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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
s = deque(input().strip())
q = int(input())
q_list = deque()
for i in range(q):
    e = deque(input().split(" "))
    q_list += [e]
for i in range(q):
    if q_list[i][0] == "1\n":
        s.reverse()
    elif q_list[i][0] == "2":
        if q_list[i][1] == "1":
            s.appendleft(q_list[i][2])
        else:
            s.append(q_list[i][2])
for i in s:
    print(i.strip(), end="")

Submission status: Time Limit Exceeded

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

def main():
    s=input().strip()
    q=int(input())
    cnt=0
    Q=[]
    for _ in range(q):
        query=input().strip()
        if query=='1':
            cnt+=1
        else:
            _,f,c=query.split()
            Q.append((cnt,int(f),c))
    if cnt%2==0:
        ans=s
    else:
        ans=s[::-1]
    for a,f,c in Q:
        if (cnt-a+f)%2==0:
            ans+=c
        else:
            ans=c+ans
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

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

read = 0
for i in range(Q):
	qurey = input().split()
	if qurey[0] == "1":
		read = (read + 1) % 2
	else:
		if read == 0:
			if qurey[1] == "1":
				S = qurey[2] + S
			else:
				S = S + qurey[2]
		else:
			if qurey[1] == "2":
				S = qurey[2] + S
			else:
				S = S + qurey[2]

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

Submission status: Time Limit Exceeded

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

for i in range(q):
    x.append(list(input().split()))

count = 0
for i in range(q):
    if len(x[i]) == 1:
        if count == 0:
            count = 1
        else:
            count = 0
    else:
         if (x[i][1] == '1' and count == 0) or (x[i][1] == '2' and count == 1):
             s = x[i][2] + s
         elif (x[i][1] == '1' and count == 1) or (x[i][1] == '2' and count == 0): 
            s = s + x[i][2] 

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

Submission status: Time Limit Exceeded

Solution code:
S = input()
Slist = [S[i] for i in range(len(S))]
Q = int(input())
Query = [list(input().split()) for i in range(Q)]
Qlen = len(Query)
cnt = 0
last = []
head = []
for i in range(Qlen):
    if int(Query[i][0]) == 1:
        cnt +=1
    else:
        if int(Query[i][1]) == 1: #頭につける
            if cnt % 2 != 0:   #逆さ
                last = last + [Query[i][2]]
            else:
                head = [Query[i][2]] + head
        else: #けつにつける
            if cnt % 2 != 0:
                head = [Query[i][2]] + head
            else:
                last = last + [Query[i][2]]
if cnt % 2 == 0:
    print("".join(head + Slist + last))
else:
    Slist = Slist[::-1]
    head = head[::-1]
    last = last[::-1]
    print("".join(last + Slist + head))
    
# head Slist last

Submission status: Time Limit Exceeded

Solution code:
# TLE
import sys
import numpy as np

# input = sys.stdin.readline

s = list(input())

n = int(input())

reverse = False
for ii in range(n):
    q = input()
#     print("".join(s))
    if q[0] == "1":
        reverse += 1
        reverse %= 2
#         s = s[::-1]
    else:
        t, f, c = q.split()
        if f == "1":
            if reverse:
                s.append(c)
            else:
                s.insert(0, c)
        else:
            if reverse:
                s.insert(0, c)
            else:
                s.append(c)
if reverse:
    s = s[::-1]
print("".join(s))

Submission status: Time Limit Exceeded

Solution code:
s=input()
n=int(input())
rev=0
for i in range(n):
  l=input()
  q=int(l[0])
  if q==1:
    if rev==1:
      rev=0
    else:
      rev=1
  else:
    f=int(l[2])
    c=l[-1]
    if (rev==0 and f==1)or(rev==1 and f==2):
      s=c+s
    else:
      s=s+c
if rev==1:
  ll=list(reversed(s))
  s="".join(ll)
print(s)

Submission status: Time Limit Exceeded

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

flag = 1
for i in range(Q):
    q =  [ i for i in input().split(' ')]
    if q[0] == '1':
        flag = flag * -1
    else:
        if flag == 1: 
            if q[1] == '1':
                S = q[2] + S
            else:
                S = S + q[2]
        else:
            if q[1] == '1':
                S = S + q[2]
            else:
                S = q[2] + S
            
if flag ==1:
    print(S)
else:
    print(S[::-1])

Submission status: Time Limit Exceeded

Solution code:
s=input()
q=int(input())
cnt=0
for i in range(q):
    j=tuple(input().split())
    if  len(j)==3 :
        if (cnt+int(j[1]))%2:
            s=j[2]+s
        else:
            l=s
            s=l+j[2]
    else:
        cnt+=1
if cnt%2==0:
    print(s)
else:
    print(s[::-1])

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys

ans = str(input())
n = int(input())
r = 2

for i in range(n) :
    x = input().split(" ")
    if int(x[0]) == 1 :
        r = r + 1
    else :
        pp = int(x[1])
        if r % 2 == 1 :
            pp = pp + 1
        if pp % 2  == 1 :
            ans = str(x[2]) + ans
        else :
            ans = ans + str(x[2])

if r % 2 == 1 :
    ans = ans[::-1]

print(ans)

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
import sys
def resolve():
    S=deque(input())
    Q,=pin()
    ans=""
    turn=0
    for i in range(Q):
        q=sys.stdin.readline().rstrip().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()

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
import sys
def resolve():
    S=deque(input())
    Q,=pin()
    ans=""
    turn=0
    for i in range(Q):
        q=sys.stdin.readline().rstrip().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()

Submission status: Time Limit Exceeded

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

S = input().rstrip()
Q = int(input())
query = [list(input().split()) for _ in range(Q)]

a = ''
ans = S
b = ''
flag = True

for i in range(Q):
    if query[i][0] == '1':
        if flag:
            flag = False
        else:
            flag = True
        continue
    elif query[i][0] == '2':
        f = query[i][1]
        c = query[i][2].rstrip()
        if f == '1' and flag:
            a = c + a
        elif f == '1' and not flag:
            b = b + c
        elif f == '2' and flag:
            b = b + c
        elif f == '2' and not flag:
            a = c + a
if flag:
    print(a + ans + b)
else:
    tmp = a + ans + b
    print(tmp[::-1])

Submission status: Time Limit Exceeded

Solution code:
s=list(input())
q=int(input())
for i in range(q):
    data=input().split()
    if(len(data)==1):
       s.reverse()
    elif(data[1]=="1"):
        s.insert(0,data[2])
    else:
        s.append(data[2])
print(''.join(s))

Submission status: Time Limit Exceeded

Solution code:
import sys
import math
mod=10**9+7
inf=float("inf")
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from functools import lru_cache
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#######ここから天ぷら########
s=deque(list(input()))
q=int(input())
rev=0
for _ in range(q):
    a=input()
    if a=="1": 
        s.reverse()
        continue
    n,m,p=map(str,a.split())
    if m=="1":
        if rev==1:
            s.append(p)
        else:
            s.appendleft(p)
    else:
        if rev==1:
            s.appendleft(p)
        else:
            s.append(p)
if rev==1:
    print("".join(list(s)[::-1]))
else:
    print(("".join(list(s))))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

S = input()
Q = int(input())
reverse_cnt = 0
index = np.array([0 for _ in range(Q)])
s = deque([])

for i in range(Q):
    query = input().split()
    if query[0] == "1":
        reverse_cnt += 1
        index = index * -1
    else:
        s.append(query[2])
        if query[1] == "1":
            index[i] = -1
        else:
            index[i] = 1

if reverse_cnt % 2 != 0:
    S = S[::-1]
    
for i in index:
    if i == 1:
        S += s.popleft()
    elif i == -1:
        S = s.popleft() + S

print(S)

Submission status: Time Limit Exceeded

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

count = 0

for query in P:
    if query[0]=="1":
        count+=1
    else:
        if query[1]=="1":
            if count%2==0:
                S=query[2]+S
            else:
                S=S+query[2]
        else:
            if count%2==0:
                S=S+query[2]
            else:
                S=query[2]+S
if count%2==1:
    S=S[::-1]
    
print(S)

Submission status: Time Limit Exceeded

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

#方向判定 順方向1、逆方向-1
d = 1 

for i in range(qn):
  q = list(map(str,input().split()))
  if q[0] == '1':
    d = -1*d
  elif d == 1:
    if q[1] == '1':
      s = q[2]+s
    elif q[1] == '2':
      s = s+q[2]
  elif d == -1:
    if q[1] == '1':
      s = s+q[2]
    elif q[1] == '2':
      s = q[2]+s

#最終順序判定
if d == -1:
  s = s[::-1]
#
print(s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
def resolve_d():
    s = np.array(list(input()))
    q = int(input())
    l = [input().split() for i in range(q)]
    r_flg = 0

    for ope_l in l:
        if ope_l[0] == '1':
            r_flg += 1 # 反転フラグを加算
        else:
            if ope_l[1] == '1':
                if r_flg % 2 == 0:
                    s = np.append(ope_l[2], s)
                else:
                    s = np.append(s, ope_l[2])
            elif ope_l[1] == '2':
                if r_flg % 2 == 0:
                    s = np.append(s, ope_l[2])
                else:
                    s = np.append(ope_l[2], s)
    if r_flg % 2 == 0:
        print(''.join(s))
    else:
        print(''.join(s[::-1]))
resolve_d()

Submission status: Time Limit Exceeded

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

    hanten = 0 # 偶数なら正常、 奇数なら反転状態

    for _ in range(q):
        tmp = input()
        if len(tmp) == 1:
            hanten += 1
        else:
            if (hanten % 2) == 0:
                if tmp[2] == '1':
                    s = tmp[4] + s
                else:
                    s = s + tmp[4]
            else:
                if tmp[2] == '1':
                    s = s + tmp[4]
                else:
                    s = tmp[4] + s

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

if __name__ == '__main__':
    main()