let split str delim =
  let rec doit s acc =
    match
      try Some (String.index s delim)
      with _ -> None
    with
    | None -> s :: acc
    | Some i ->
        let s1 = String.sub s 0 i in
        let s2 = String.sub s (i + 1) (String.length s - String.length s1 - 1) in
        doit s2 (s1 :: acc)
  in
  List.rev (doit str [])

let string_fold_left f init str =
  let n = String.length str in
  let rec doit i acc =
    if i >= n then acc
    else doit (i + 1) (f acc str.[i])
  in
  doit 0 init

let swap (a, b) = (b, a)

let make_dice = function
  | a :: b :: c :: d :: e :: f :: _ -> [(a, f); (b, e); (c, d)]
  | _ -> exit 1

let roll dice cmd =
  match dice with
  | [] | [_] | _::_::[] -> exit 1
  | x :: y :: z :: _ ->
      match cmd with
      | 'N' -> [y; swap x; z]
      | 'S' -> [swap y; x; z]
      | 'E' -> [swap z; y; x]
      | 'W' -> [z; y; swap x]
      | _ -> exit 1

let multi_roll dice cmds =
  string_fold_left (fun acc c -> roll acc c) dice cmds

let rotate_clockwise = function
  | [] | [_] | _::_::[] -> exit 1
  | x :: y :: z :: _ -> [x; z; swap y]

let all_rolled_patterns dice =
  let pin_top d =
    [d; roll d 'N'; roll d 'W'; roll d 'E'; roll d 'S'; multi_roll d "SS"]
  in
  let rotate d =
    let d1 = rotate_clockwise d in
    let d2 = rotate_clockwise d1 in
    let d3 = rotate_clockwise d2 in
    [d; d1; d2; d3]
  in
  List.concat (List.map rotate (pin_top dice))

let top = function
  | [] | [_] | _::_::[] -> exit 1
  | (a, _) :: _ -> a

let front = function
  | [] | [_] | _::_::[] -> exit 1
  | _ :: (b, _) :: _ -> b

let right = function
  | [] | [_] | _::_::[] -> exit 1
  | _ :: _ :: (c, _) :: _ -> c

let () =
  let l = read_line () in
  let dice = make_dice (List.map int_of_string (split l ' ')) in
  let q = read_int () in
  let rec doit i =
    if i > q then ()
    else
      let l = read_line () in
      match List.map int_of_string (split l ' ') with
      | [] | [_] -> exit 1
      | n_top :: n_front :: _ -> begin
          let ds = List.filter (fun d ->
            n_top = top d && n_front = front d) (all_rolled_patterns dice) in
          Printf.printf "%d\n" (right (List.hd ds));
          doit (i + 1);
        end
  in
  doit 1