Problem:
Deque For a dynamic array $A = \{a_0, a_1, ...\}$ of integers, perform a sequence of the following operations:  push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.  randomAccess($p$): Print element $a_p$.  pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.  $A$ is a 0-origin array and it is empty in the initial state. Input The input is given in the following format. $q$
$query_1$
$query_2$
:
$query_q$ Each query $query_i$ is given by 0 $d$ $x$ or 1 $p$ or 2 $d$ where the first digits 0 , 1 and 2 represent push, randomAccess and pop operations respectively. randomAccess and pop operations will not be given for an empty array. Output For each randomAccess, print $a_p$ in a line. Constraints  $1 \leq q \leq 400,000$  $0 \leq p < $ the size of $A$  $-1,000,000,000 \leq x \leq 1,000,000,000$  Sample Input 1 11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1 Sample Output 1 2
1
3
4
1

Solution (Python):


from collections import deque

n = int(input())
word = deque()

for i in range(n):
    command = list(map(int, input().split()))
    if command[0] == 0:
        if command[1] == 0:
            word.insert(0, command[2])
        else:
            word.append(command[2])
    elif command[0] == 1:
        print('{0}'.format(word[command[1]]))
    elif command[0] == 2:
        if command[1] == 1:
            word.pop()
        else:
            word.popleft()

Solution (Python):
from sys import stdin
from collections import deque

num = int(input())

q = deque()

for i in range(num):
	cmd = stdin.readline().strip().split()
	if cmd[0] == "0":
		if cmd[1] == "0":
			q.appendleft(cmd[2])
		else:
			q.append(cmd[2])
	elif cmd[0] == "1":
		print(q[int(cmd[1])],sep='\n')
	else:
		if cmd[1] == "0":
			q.popleft()
		else:
			q.pop()

Solution (Python):
from collections import deque
cnt = int(input())
a = deque()

for i in range(cnt):
    li = list(map(int,input().split()))
    if li[0] == 0:
        if li[1] == 0:
            a.appendleft(li[2])
        else:
            a.append(li[2])
    if li[0] == 1:
        print(a[li[1]])
    if li[0] ==2:
        if li[1]==0:
            a.popleft()
        else:
            a.pop()

Solution (Python):

"""
Created on Sat May 19 15:10:55 2018
AOJ ITP2_1_B
@author: maezawa
"""

q = int(input())
a = [0 for _ in range(8000000)]
start = 4000000
end = 4000001
for i in range(q):
    ops = list(map(int,input().split()))
    if ops[0] == 0:
        if ops[1] == 0:
            a[start] = ops[2]
            start -= 1
        else:
            a[end] = ops[2]
            end += 1
    elif ops[0] == 1:
        print(a[start+ops[1]+1])
    elif ops[0] == 2:
        if ops[1] == 0:
            start += 1
        elif ops[1] == 1:
            end -= 1

Solution (Python):
from collections import deque

n = int(input())
d = deque()

for i in range(n):
    cmd = [int(i) for i in input().split()]

    if cmd[0] == 0:
        if cmd[1] == 0: d.appendleft(cmd[2])
        else: d.append(cmd[2])

    elif cmd[0] == 1:
        print(d[cmd[1]])

    elif cmd[0] == 2:
        if cmd[1] == 0: d.popleft()
        else: d.pop()

Solution (Python):
from collections import deque

deq = deque([])

q = int(input())
for i in range(q):
    op = list(map(int, input().split(' ')))
    if op[0] == 0:
        if op[1] == 0:
            deq.appendleft(op[2])
        else:
            deq.append(op[2])
    elif op[0] == 1:
        print(deq[op[1]])
    elif op[0] == 2:
        if op[1] == 0:
            deq.popleft()
        else:
            deq.pop()

Solution (Python):

from math import ceil, floor, log2


class Node:
    __slots__ = ('value', 'prev', 'next', 'pskip', 'nskip')

    def __init__(self, value):
        self.value = value
        self.prev = None
        self.next = None
        self.pskip = None
        self.nskip = None

    def __str__(self):
        return '<Node({})>'.format(self.value)


class Deque:
    SKIPSIZE = 128

    def __init__(self):
        self.count = 0
        self.head = Node(None)
        self.tail = Node(None)
        self.head.next = self.tail
        self.index = []
        self.tail.prev = self.head

    def push(self, value):
        node = Node(value)
        node.prev = self.tail.prev
        node.next = self.tail
        self.tail.prev.next = node
        self.tail.prev = node
        self.count += 1
        self._add_index(node)
        self._add_pskip(node)

    def push_left(self, value):
        node = Node(value)
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node
        self.count += 1
        self._add_index_left(node)
        self._add_nskip(node)

    def pop(self):
        node = self.tail.prev
        self.tail.prev = node.prev
        node.prev.next = self.tail
        self.count -= 1
        self._remove_index()
        self._remove_pskip(node)
        return node.value

    def pop_left(self):
        node = self.head.next
        self.head.next = node.next
        node.next.prev = self.head
        self.count -= 1
        self._remove_index_left()
        self._remove_nskip(node)
        return node.value

    def _add_pskip(self, node):
        if self.count >= self.SKIPSIZE:
            if node.prev.pskip is None:
                pnode = node
                for _ in range(self.SKIPSIZE):
                    pnode = pnode.prev
            else:
                pnode = node.prev.pskip.next
            node.pskip = pnode
            pnode.nskip = node

    def _add_nskip(self, node):
        if self.count >= self.SKIPSIZE:
            if node.next.nskip is None:
                nnode = node
                for _ in range(self.SKIPSIZE):
                    nnode = nnode.next
            else:
                nnode = node.next.nskip.prev
            node.nskip = nnode
            nnode.pskip = node

    def _remove_pskip(self, node):
        if node.pskip is not None:
            node.pskip.nskip = None
            node.pskip = None

    def _remove_nskip(self, node):
        if node.nskip is not None:
            node.nskip.pskip = None
            node.nskip = None

    def _add_index(self, node):
        exp = ceil(log2(self.count))
        if self.count == 2**exp:
            
            self.index.append(node)

    def _add_index_left(self, node):
        self.index = [n.prev for n in self.index]
        self._add_index(self.tail.prev)

    def _remove_index(self):
        if self.count == 0:
            
            self.index.pop()
            return
        exp = ceil(log2(self.count))
        if self.count == 2**exp - 1:
            
            self.index.pop()

    def _remove_index_left(self):
        index = [n.next for i, n in enumerate(self.index) if i > 0]
        index.insert(0, self.head.next)
        self.index = index
        self._remove_index()

    def _select_index(self, n):
        exp = floor(log2(n+1))
        p1 = 2**exp
        p2 = 2**(exp+1)
        step = n - p1 + 1
        chunksize = min(p2, self.count) - p1 + 1
        if step > chunksize // 2:
            if p2 > self.count:
                node = self.tail.prev
                step -= chunksize-1
            else:
                node = self.index[exp+1]
                step -= chunksize-1
            while -step > self.SKIPSIZE:
                if node.pskip is None:
                    break
                node = node.pskip
                step += self.SKIPSIZE
        else:
            node = self.index[exp]
            while step > self.SKIPSIZE:
                if node.nskip is None:
                    break
                node = node.nskip
                step -= self.SKIPSIZE
        return (node, step)

    def __getitem__(self, key):
        if key is slice:
            raise NotImplemented()

        n = int(key)
        if n < 0:
            n = self.count + n
        if n >= self.count or n < 0:
            raise IndexError()

        node, sp = self._select_index(n)
        
        
        if sp < 0:
            for i in range(-sp):
                node = node.prev
        else:
            for i in range(sp):
                node = node.next

        return node.value


def run():
    n = int(input())
    deque = Deque()

    for _ in range(n):
        command = input()
        if command.startswith('0'):
            sub, val = [int(x) for x in command[2:].split()]
            if sub == 0:
                deque.push_left(val)
            elif sub == 1:
                deque.push(val)
            else:
                raise ValueError('subcommand of push')
        elif command.startswith('1'):
            i = int(command[2:])
            print(deque[i])
        elif command.startswith('2'):
            sub = int(command[2:])
            if sub == 0:
                deque.pop_left()
            elif sub == 1:
                deque.pop()
            else:
                raise ValueError('subcommand of pop')
        else:
            raise ValueError('invalid command')


if __name__ == '__main__':
    run()

Solution (Python):
from collections import deque

arr = deque()

for _ in range(int(input())):
    cmd = [int(x) for x in input().split()]

    if cmd[0] == 0:
        if cmd[1]:
            arr.append(cmd[2])
        else:
            arr.appendleft(cmd[2])
    elif cmd[0] == 1:
        print(arr[cmd[1]])
    else:
        if cmd[1]:
            arr.pop()
        else:
            arr.popleft()

Solution (Python):


from collections import deque

d = deque()
q = int(raw_input())

for i in range(q):
    query = [int(j) for j in raw_input().split()]
    if query[0] == 0:
        if query[1] == 0:
            d.appendleft(query[2])
        else:
            d.append(query[2])
    elif query[0] == 1:
        print  d[query[1]]
    elif query[0] == 2:
        if query[1] == 0:
            d.popleft()
        else:
            d.pop()

Solution (Python):
from collections import deque
 
d = deque()
q = int(raw_input())
 
for i in range(q):
    query = [int(j) for j in raw_input().split()]
    if query[0] == 0:
        if query[1] == 0:
            d.appendleft(query[2])
        else:
            d.append(query[2])
    elif query[0] == 1:
        print  d[query[1]]
    elif query[0] == 2:
        if query[1] == 0:
            d.popleft()
        else:
            d.pop()

Solution (Python):
from collections import deque

def push(duque, d, x):
    if d == 1:
        duque.append(x)
    else:
        duque.appendleft(x)
    return duque

def randomAccess(duque, p):
    print(duque[p])

def pop(duque, d):
    if d == 1:
        duque.pop()
    else:
        duque.popleft()
    return duque

if __name__ == '__main__':
    l = deque([])
    n = int(input())
    for i in range(n):
        j= input().split()

        if int(j[0]) == 0:
            push(l, int(j[1]), int(j[2]))
        elif int(j[0]) == 1:
            randomAccess(l, int(j[1]))
        else:
            pop(l, int(j[1]))

Solution (Python):


from collections import deque

A = deque([])
N = int(input())
for i in range(N):
    query = list(map(int, input().split()))
    if query[0] == 0:
        if query[1] == 0:
            A.appendleft(query[2])
        elif query[1] == 1:
            A.append(query[2])
    elif query[0] == 1:
        print(A[query[1]])
    elif query[0] == 2:
        if query[1] == 0:
            A.popleft()
        if query[1] == 1:
            A.pop()

Solution (Python):



from collections import deque
Q = deque()
q = int(input())
for i in range(q):
	a = input()
	if   a[0] == '0': 
		if a[2] == '0': Q.appendleft(a[4:])
		else          : Q.append(a[4:])
	elif a[0] == '1': print(Q[int(a[2:])]) 
	else: 
		if a[2] == '0': Q.popleft()
		else:           Q.pop()

Solution (Python):

"""
Created on Sun Jun 24 14:53:50 2018
ITP21B
@author: maezawa
"""

from collections import deque

d = deque()

n = int(input())

for i in range(n):
    c = list(map(int, input().split()))
    if c[0] == 0:
        if c[1] == 0:
            d.appendleft(c[2])
        else:
            d.append(c[2])
    elif c[0] == 1:
        print(d[c[1]])
    else:
        if c[1] == 0:
            d.popleft()
        else:
            d.pop()

Solution (Python):



from collections import deque
Q = deque()
q = int(input())
for i in range(q):
	a = input()
	if   a[0] == '0': 
		if a[2] == '0': Q.appendleft(a[4:])
		else          : Q.append(a[4:])
	elif a[0] == '1': print(Q[int(a[2:])]) 
	else: 
		if a[2] == '0': Q.popleft()
		else:           Q.pop()

Solution (Python):
from collections import deque
A = deque()
n = int(input())
for i in range(n):
    tmp = input().split()

    if tmp[0] == "0" and tmp[1] == "0":
        A.appendleft(tmp[2])
    elif tmp[0] == "0" and tmp[1] == "1":
        A.append(tmp[2])
    elif tmp[0] == "1":
        print(A[int(tmp[1])])
    elif tmp[1] == "0":
        A.popleft()
    else:
        A.pop()

Solution (Python):
from collections import deque

Q = deque()
q=int(input())

for _ in range(q):
    a = input().split()
    
    if a[0] == "0":
        if a[1] == "0":
            Q.appendleft(a[2])
        else:
            Q.append(a[2])
    elif a[0] == "1":
        print(Q[int(a[1])])
    else:
        if a[1] == "0":
            Q.popleft()
        else:
            Q.pop()

Solution (Python):
from collections import deque

q = int(input())
A = deque()

for i in range(q):
    query = str(input())
    if query[0] == "0": 
        if query[2] == "0":
            A.appendleft(int(query[4:]))
        else:
            A.append(query[4:])
    elif query[0] == "1": 
        print(A[int(query[2:])])
    else: 
        if query[2] == "0":
            A.popleft()
        else:
            A.pop()

Solution (Python):
from collections import deque
A = deque()
ans = []


def push(d, x):
    global A
    if d == 0:
        A.appendleft(x)
    elif d == 1:
        A.append(x)


def randomAccess(p):
    global A, ans
    if A != []:
        ans.append(A[p])
    else:
        print('RandomAccessError')


def pop(d):
    global A
    if d == 0:
        A.popleft()
    elif d == 1:
        A.pop()


def main():
    q = input()

    for i in range(int(q)):
        command = input().split()
        if len(command) == 3:
            query, operation, number = (int(x) for x in command)
            push(operation, number)
        else:
            query, number = (int(x) for x in command)
            if query == 1:
                randomAccess(number)
            else:
                pop(number)

    for i in range(len(ans)):
        print(ans[i])


if __name__ == "__main__":
    main()

Solution (Python):
import sys
from collections import deque

A = deque()

Q = int(sys.stdin.readline().rstrip())
for _ in range(Q):
    s = sys.stdin.readline().rstrip().split()
    if s[0] == "0":  
        if s[1] == "0":
            A.appendleft(s[2])
        else:
            A.append(s[2])
    elif s[0] == "1":  
        print(A[int(s[1])])
    else:
        if s[1] == "0":
            A.popleft()
        else:
            A.pop()

Solution (Python):

from collections import deque
Q = deque()
q = int(input())
for i in range(q):
	a = input()
	if a[0] == '0':  
		if a[2] == '0':
			Q.appendleft(a[4:])
		else:
			Q.append(a[4:])
	elif a[0] == '1':
		print(Q[int(a[2:])])  
	else:  
		if a[2] == '0':
			Q.popleft()
		else:
			Q.pop()

Solution (Python):
def resolve():
    from collections import deque
    q = int(input())
    ans = deque()
    for _ in range(q):
        q = [int(i) for i in input().split()]
        if q[0] == 2:
            if q[1] == 0:
                ans.popleft()
            else:
                ans.pop()
        else:
            if q[0] == 0:
                if q[1] == 0:
                    ans.appendleft(q[2])
                else:
                    ans.append(q[2])
            else:
                print(ans[q[1]])


resolve()

Solution (Python):
from collections import deque
N = int(input())
Q = deque()

for _ in range(N):
    order = list(map(int,input().split()))
    if order[0] == 0:
        if order[1] == 0:
            Q.appendleft(order[2])
        else:
            Q.append(order[2])
    elif order[0] == 1:
        print(Q[order[1]])
    else:
        if order[1] == 0:
            Q.popleft()
        else:
            Q.pop()

Solution (Python):
from collections import deque

A = deque()

n = int(input())
for i in range(n):
    q = input()
    if q[0] == "0":
        if q[2] == "0":
            A.appendleft(q[4:])
        else:
            A.append(q[4:])
    elif q[0] == "1":
        print(A[int(q[2:])])
    else:
        if q[2] == "0":
            A.popleft()
        else:
            A.pop()

Solution (Python):
from collections import deque

class MyDeque:
    def __init__(self):
        self.data = deque()

    def push(self, d, x):
        if d == 0:
            self.data.appendleft(x)
        elif d == 1:
            self.data.append(x)

    def random_access(self, p):
        print(self.data[p])

    def pop(self, d):
        if d == 0:
            self.data.popleft()
        elif d == 1:
            self.data.pop()

my_deque = MyDeque()
q = int(input())

for _ in range(q):
    args = input().split(' ')
    if args[0] == '0':
        d = int(args[1])
        x = int(args[2])
        my_deque.push(d, x)

    elif args[0] == '1':
        p = int(args[1])
        my_deque.random_access(p)

    elif args[0] == '2':
        d = int(args[1])
        my_deque.pop(d)

Solution (Python):
from collections import deque
q=int(input())
lis=deque()
lq=[]
for i in range(q):
	lq.append([int(x) for x in input().split(' ')])

for i in lq:
	order=i[0]
	if order==0:
		d=i[1]
		if d==0:
			lis.appendleft(i[2])
		else:
			lis.append(i[2])
	elif order==1:
		print(lis[i[1]])
	elif order==2:
		d=i[1]
		if d==0:
			lis.popleft()
		else:
			lis.pop()

Solution (Python):
from collections import deque
que = deque([])
Q = int(input())

for _ in range(Q):
    query = list(map(int, input().split()))
    if query[0] == 0:
        _, d, x = query
        if d:
            que.append(x)
        else:
            que.appendleft(x)
    elif query[0] == 1:
        print(que[query[1]])
    else:
        _, d = query
        if d:
            que.pop()
        else:
            que.popleft()

Solution (Python):
from collections import deque
num = int(input())
A = deque()

for i in range(num):
    queryi = list(map(int, input().split()))

    if queryi[0] == 1:
        print(A[queryi[1]])

    elif queryi[0] == 2:
        if queryi[1] == 0:
            A.popleft()
        else:
            A.pop()

    else:
        if queryi[1] ==0:
            A.appendleft(queryi[2])
        else:
            A.append(queryi[2])

Solution (Python):
from collections import deque

n = int(input())
num_list = []
for i in range(n):
    num_list.append(list(map(int,input().split())))

num_of_operations = num_list[0][0]

vec = deque('')

for i in range(len(num_list)):
    operation = num_list[i][0]

    if(operation == 0):
        d = num_list[i][1]
        if(d == 0): vec.appendleft(num_list[i][2])
        elif(d == 1): vec.append(num_list[i][2])
            
            
    elif(operation == 1):
        p = num_list[i][1]
        print(vec[p])

    elif(operation == 2):
        d = num_list[i][1]
        if(d == 0): vec.popleft() 
        elif(d == 1): vec.pop()

Solution (Python):
from collections import deque

A = deque()


def pushBack(op,x):
  if op == 0:
    A.appendleft(x)
  else:
    A.append(x)


def randomAccess(x):
  print(A[x])
  

def popBack(op):
  if op == 0:
    A.popleft()
  else:
    A.pop()


cmdList = [ pushBack, randomAccess, popBack ]
n = int(input())

for i in range(n):
  cmd = input()
  if cmd.startswith("0"):
    c,o,x = map(int,cmd.split(" "))
    cmdList[0](o,x)
  if cmd.startswith("1"):
    c,param = map(int,cmd.split(" "))
    cmdList[1](param)
  if cmd.startswith("2"):
    c,o = map(int,cmd.split(" "))
    cmdList[2](o)

Solution (Python):

import sys
from collections import deque
q = int(input())
S = deque()
for i in range(q):
    l = list(map(int,input().split()))
    if l[0] == 0:
        if l[1] == 0:
            S.appendleft(l[2])
        else:
            S.append(l[2])
    elif l[0] == 1:
        print(S[l[1]])
    else:
        if l[1] == 0:
            S.popleft()
        else:
            S.pop()

Solution (Python):
from collections import deque

q = int(input())
querys = [list(map(int, input().split())) for _ in range(q)]

d = deque()

for query in querys:
    if query[0] == 0:
        if query[1] == 0:
            d.appendleft(query[2])
        else:
            d.append(query[2])

    if query[0] == 1:
        print(d[query[1]])

    if query[0] == 2:
        if query[1] == 0:
            d.popleft()
        else:
            d.pop()

Solution (Python):
from collections import deque

def push(a, d, x):
    if d == 0: a.appendleft(x)
    elif d == 1: a.append(x)
def randomAccess(a, p):
    print(a[p])
def pop(a, d):
    if d == 0: _=a.popleft()
    elif d == 1: _=a.pop()

a = deque()
q = int(input())
for _ in range(q):
    query = list(map(int, input().split()))
    if query[0]==0: push(a, query[1], query[2])
    elif query[0]==1: randomAccess(a, query[1])
    elif query[0]==2: pop(a, query[1])

Solution (Python):
from collections import deque

que = deque()
q = int(input())

for i in range(q):
    query = input().split()

    if query[0] == "0":
        if query[1] == "0":
            que.appendleft(query[2])
        else:
            que.append(query[2])
    elif query[0] == "1":
        print(que[int(query[1])])
    else:
        if query[1] == "0":
            que.popleft()
        else:
            que.pop()

Solution (Python):
from collections import deque

q = int(input())
data_list = list()
for i in range(q):
    data = input()
    data_list.append(data)

a = deque()
for data in data_list:
    if data[0] == "0":
        if data.split()[1] == "1":
            a.append(data.split()[2])
        else:
            x = data.split()[2]
            a.appendleft(x)
        
    elif data[0] == "1":
        print(a[int(data.split()[1])])
        
    else:
        if data.split()[1] == "1":
            a.pop()
        else:
            a.popleft()

Solution (Python):
import collections
q = int(input())
dq = collections.deque()
ans = []
while q:
    q -= 1
    s = input().split()
    if s[0] == '0':
        if s[1] == '0':
            dq.appendleft(s[2])
        else:
            dq.append(s[2])
    elif s[0] == '1':
        ans.append(dq[int(s[1])])
    else:
        if s[1] == '0':
            dq.popleft()
        else:
            dq.pop()
print('\n'.join(ans))

Solution (Python):
from collections import deque
Q = deque()
q = int(input())
for i in range(q):
    a = input().split()
    if a[0] == "0":
        if a[1] == "1":Q.append(a[2])
        else: Q.appendleft(a[2])
    elif a[0] == "1": print(Q[int(a[1])])
    else:
        if a[1] =="1":Q.pop()
        else: Q.popleft()

Solution (Python):
from collections import deque

d = deque()
q = int(input())
for i in range(q):
    a, *b = map(int, input().split())
    if a == 0:
        if b[0] == 0:
            d.appendleft(b[1])
        else:
            d.append(b[1])
    elif a == 1:
            print(d[b[0]])
    else:
        if b[0] == 0:
            d.popleft()
        else:
            d.pop()

Solution (Python):
from  collections import deque

d=deque()
n=int(input())
for i in range(n):
    q=list(map(int,input().split()))
    if q[0]==0:
        if q[1]==0:
            d.appendleft(q[2])
        else:
            d.append(q[2])
    elif q[0]==1:
        print(d[q[1]])
    else:
        if q[1]==0:
            d.popleft()
        else:
            d.pop()

Solution (Python):
from collections import deque

d = deque()
n = int(input())
for _ in range(n):
    q = list(map(int,input().split()))
    if q[0] == 0:
        if q[1] == 0:d.appendleft(int(q[2]))
        else        :d.append(int(q[2]))
    if q[0] == 1:
        print (d[int(q[1])])
    if q[0] == 2:
        if q[1]==0:d.popleft()
        else      :d.pop()

Solution (Python):
from collections import deque

ans=deque([])

for _ in range(int(input())):
    
    a=list(map(int,input().split()))
    
    if len(a)==3:
        if a[1]==0: ans.appendleft(a[2])
        
        else: ans.append(a[2])
        
    if len(a)==2:
        
        if a[0]==1 : print(ans[a[1]])
        
        else: 
            
            if a[1]==0: ans.popleft()
            
            else: ans.pop()

Solution (Python):
from collections import deque

n = int(input())
ans = deque()


for i in range(n):
    m = list(map(int,input().split()))
    if m[0] == 0:
        if m[1] == 0:
            ans.appendleft(m[2])
        else:
            ans.append(m[2])
    elif m[0] == 1:
        print(ans[m[1]])
    
    elif m[0] == 2:
        if m[1] == 0:
            ans.popleft()
        else:
            ans.pop()

Solution (Python):
from collections import deque
num=int(input())
A=deque()
for i in range(num):
    lst=list(map(int,input().split()))
    if lst[0]==0:
      if lst[1]==0:
        A.appendleft(lst[2])
      else :A.append(lst[2])
    elif lst[0]==1:
        print(A[lst[1]])
    elif lst[0]==2:
      if lst[1]==0:
         A.popleft()  
      else :A.pop()

Solution (Python):
import itertools

def spaced_to_ints(spaced_some):
    return [int(a) for a in spaced_some.split(" ")]

def order_sequence_chars(str):
    return list(str)

def count_order(order):
    return(int(order))

def get_dice():
    input_data = input().split(" ")
    items = [int(cont) for cont in input_data]
    keys = ['T', 'S', 'E', 'W', 'N', 'B']
    return dict(zip(keys, items))

def rot_dice(rot, dice):
    if rot == "N":
        keys = ['T', 'S', 'B', 'N']
        items = dice['S'], dice['B'], dice['N'], dice['T']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

    if rot == "S":
        keys = ['T', 'S', 'B', 'N']
        items = dice['N'], dice['T'], dice['S'], dice['B']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

    if rot == "E":
        keys = ['T', 'E', 'B', 'W']
        items = dice['W'], dice['T'], dice['E'], dice['B']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

    if rot == "W":
        keys = ['T', 'E', 'B', 'W']
        items = dice['E'], dice['B'], dice['W'], dice['T']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

    if rot == "R":
        keys = ['N', 'W', 'S', 'E']
        items = dice['E'], dice['N'], dice['W'], dice['S']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

    if rot == "L":
        keys = ['N', 'W', 'S', 'E']
        items = dice['W'], dice['S'], dice['E'], dice['N']
        new_dice = dict(zip(keys, items))
        dice.update(new_dice)

def search_right_surf(conds, dice):
    a, b = conds
    a_key = [k for k, v in dice.items() if v == a]
    b_key = [k for k, v in dice.items() if v == b]
    key_list = a_key + b_key

    part_st = ''.join(key_list)

    def search(part_st):
        if part_st in "TNBST":
            return "W"

        if part_st in "TSBNT":
            return "E"

        if part_st in "TEBWT":
            return "N"

        if part_st in "TWBET":
            return "S"

        if part_st in "NESWN":
            return "B"

        if part_st in "NWSEN":
            return "T"

    target_key = search(part_st)
    print(dice[target_key])

def search_top_surf(top_surf, dice):

    dice2_surf, *_ = [k for k, v in dice.items() if v == top_surf]

    if dice2_surf == 'N':
        rot_dice("S", dice)

    if dice2_surf == 'B':
        controls = list("SS")
        for i in controls:
            rot_dice(i, dice)
    if dice2_surf == 'S':
        controls = list("N")
        for i in controls:
            rot_dice(i, dice)
    if dice2_surf == 'W':
        controls = list("E")
        for i in controls:
            rot_dice(i, dice)
    if dice2_surf == 'E':
        controls = list("W")
        for i in controls:
            rot_dice(i, dice)

def search_flont_surf(flont_surf, dice):

    dice2_surf, *_ = [k for k, v in dice.items() if v == flont_surf]

    if dice2_surf == 'E':
        controls = list("R")
        for i in controls:
            rot_dice(i, dice)

    if dice2_surf == 'S':
        controls = list("RR")
        for i in controls:
            rot_dice(i, dice)

    if dice2_surf == 'W':
        rot_dice("L", dice)

def rot_compare(dice1, dice2):

    def compare_dice(dice1, dice2):
        if dice1 == dice2:
            return True

    comb = ["N", "S", "E", "W", "R", "L"]
    tups = list()
    for i in range(6):
        tups.append(itertools.combinations(comb, i))

    if compare_dice(dice1, dice2):
        return True

    for commands in itertools.chain.from_iterable(tups):
        for command in commands:
            rot_dice(command, dice2)
            if compare_dice(dice1, dice2):
                return True
    return False

def compare_many_dices(dice_list):
    dice1 = dice_list.pop(0)
    for dice2 in dice_list:
        if rot_compare(dice1, dice2):
            return True
    return False

def q1():

    dice = get_dice()
    controls = list(input())
    for i in controls:
        rot_dice(i, dice)
    print(dice["T"])

def q2():

    dice = get_dice()
    a = input()
    repeater = int(a)

    for neee in range(repeater):
        control_input = input().split(" ")
        conds = [int(i) for i in control_input]
        search_right_surf(conds, dice)

def q3():
    dice1 = get_dice()
    dice2 = get_dice()

    if rot_compare(dice1, dice2):
        print("Yes")
    else:
        print("No")

def q4():
    inp = input()
    dice_num = int(inp)
    dice_list = list()
    for i in range(dice_num):
        dice_list.append(get_dice())

    if compare_many_dices(dice_list):
        print("No")

    else:
        print("Yes")

def alds1():
    n = int(input())
    A = [int(cont) for cont in input().split(" ")]

    print(' '.join(map(str, A)))

    for _i in range(len(A)-1):
        i = _i+1
        v = A[i]
        j = i-1

        while j >= 0:
            if A[j] < v:
                break

            A[j+1] = A[j]
            A[j] = v
            j = j - 1

        print(' '.join(map(str, A)))








def list_head():
    return 0

def list_end():
    return -1

def pushBack(li, dist, num):
    if dist == 0:
        li.insert(dist, num)
    if dist == -1:
        li.append(num)

def randomAccess(li, dist):
    print(li[dist])

def popBack(li, dist):
    if dist == 0:
        li.popleft()

    if dist == -1:
        li.pop()



def itp2_1_a():

    def func_allocate(mylist, inp):
        

        order, *others = spaced_to_ints(inp)

        if others:
            num = others[0]

        if order == 0:
            pushBack(mylist, num, list_end())

        if order == 1:
            randomAccess(mylist, num)

        if order == 2:
            popBack(mylist, list_end())

    mylist = list()
    count = count_order(input())

    for i in range(count):
        func_allocate(mylist, input())


def itp2_1_b():
    from collections import deque
    def alloc(dist):
        if dist == 0:
            return list_head()
        if dist == 1:
            return list_end()

    def func_allocate(mylist, inp):

        
        order = spaced_to_ints(inp)
        mode = order.pop(0)

        if mode == 0:
            dist = alloc(order.pop(0))
            num = order.pop(0)
            pushBack(mylist, dist, num)

        if mode == 1:
            dist = order.pop(0)
            randomAccess(mylist, dist)

        if mode == 2:
            dist = alloc(order.pop(0))
            popBack(mylist, dist)

    mydeq = deque()
    count = count_order(input())
    for i in range(count):
        func_allocate(mydeq, input())

itp2_1_b()