type dice = {
  one : int ;
  two : int ;
  three : int ;
  four : int ;
  five : int ;
  six : int };;

let roll dir dice  =
  match dir with
    "W" -> {dice with one = dice.three;
                      three = dice.six;
                      six = dice.four;
                      four = dice.one}
  | "E" -> {dice with one = dice.four;
                      four = dice.six;
                      six = dice.three;
                      three = dice.one}
  | "S" -> {dice with one = dice.five;
                      two = dice.one;
                      six = dice.two;
                      five = dice.six}
  | "N" -> {dice with one = dice.two;
                      two = dice.six;
                      six = dice.five;
                      five = dice.one}
  | _ -> dice ;;

let spin dir dice = match dir with
    "L" -> {dice with two = dice.three;
                      three = dice.five;
                      five = dice.four;
                      four = dice.two}
  | "R" -> {dice with two = dice.four;
                      four = dice.five;
                      five = dice.three;
                      three = dice.two}
  | _ -> dice ;;

 
let top_is_eq_to m dice =
  let w = roll "W" dice in
  let e = roll "E" dice in
  let n = roll "N" dice in
  let s = roll "S" dice in
  if m = dice.one then dice
  else if m = w.one then w
  else if m = e.one then e
  else if m = n.one then n
  else if m = s.one then s
  else roll "W" w ;;

let front_is_eq_to m dice =
  let l = spin "L" dice in
  let r = spin "R" dice in
  if m = dice.two then dice
  else if m = l.two then l
  else if m = r.two then r
  else spin "L" l ;;

let () =
  let as_ = Array.init 6 (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  let dice = {one = as_.(0); two = as_.(1); three = as_.(2); four = as_.(3); five = as_.(4); six = as_.(5)} in
  let n = Scanf.scanf "%d\n" (fun a -> a) in
  let rec loop i = 
    if i = 0 then ()
    else let top, front = Scanf.scanf "%d %d\n" (fun a b -> a, b) in
         ((top_is_eq_to top dice) |> front_is_eq_to front).three |> Printf.printf "%d\n";
         loop (i-1)
  in
  loop n ;;

