h = {}
min = 0
max = 1

STDIN.gets.to_i.times do
  q = STDIN.gets.split
  case q[0]
  when '0' then
    if q[1] == '0'
      h[min] = q[2]
      min -= 1
    else
      h[max] = q[2]
      max += 1
    end
  when '1' then
    idx = q[1].to_i + min + 1
    puts h[idx]
  when '2' then
    if q[1] == '0'
      h.delete(min + 1)
      min += 1
    else
      h.delete(max - 1)
      max -= 1
    end
  end
end

