open Scanf

module IntSet = Set.Make (
                    struct
                      type t = int
                      let compare (a : int) b = compare a b
                    end)

let find_min_cost costs p q =
  let best_costs = Array.make (Array.length costs) max_int in
  let neighbors p committed =
    Array.mapi (fun i cost -> (i, cost)) costs.(p)
    |> Array.fold_left
         (fun neighbors (i, cost) ->
          if cost = max_int || IntSet.mem i committed then neighbors
          else IntSet.add i neighbors)
         IntSet.empty in
  let find_best_neighbor open_ =
    IntSet.fold
      (fun i best -> if best_costs.(i) < best_costs.(best) then i else best)
      open_ (IntSet.choose open_) in
  let commit_best_neighbor committed open_ =
    let best = find_best_neighbor open_ in
    let committed = IntSet.add best committed in
    let new_opened = neighbors best committed in
    IntSet.iter
      (fun new_opened ->
       let cost = best_costs.(best) + costs.(best).(new_opened) in
       if cost < best_costs.(new_opened) then best_costs.(new_opened) <- cost)
      new_opened;
    let open_ = IntSet.union (IntSet.remove best open_) new_opened in
    (committed, open_) in
  let rec find_min_cost committed open_ =
    if IntSet.mem q committed then best_costs.(q)
    else
      let committed, open_ = commit_best_neighbor committed open_ in
      find_min_cost committed open_ in
  best_costs.(p) <- 0;
  let committed, open_ =
    commit_best_neighbor IntSet.empty (IntSet.of_list [p]) in
  find_min_cost committed open_

let read_lines n =
  let rec read_lines n acc =
    if n = 0 then List.rev acc
    else read_lines (pred n) ((read_line ())::acc) in
  read_lines n []

let rec solve () =
  let n, m = sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
  if n = 0 && m = 0 then ()
  else
    let costs = Array.make_matrix (m + 1) (m + 1) max_int in
    let times = Array.make_matrix (m + 1) (m + 1) max_int in
    read_lines n
    |> List.iter (fun line ->
                  sscanf line "%d %d %d %d"
                         (fun a b cost time ->
                          costs.(a).(b) <- cost;
                          costs.(b).(a) <- cost;
                          times.(a).(b) <- time;
                          times.(b).(a) <- time));
    let k = int_of_string (read_line ()) in
    read_lines k
    |> List.iter (fun line ->
                  sscanf line "%d %d %d"
                         (fun p q r ->
                          let costs = if r = 0 then costs else times in
                          find_min_cost costs p q |> print_int;
                          print_newline ()));
    solve ()

let () = solve ()