def dijekstra(start, nodes, value_as_dist)
  n = nodes.size
  dist = Array.new(n) { Float::INFINITY }
  is_fixed = Array.new(n) { false }
  queue = [*0...n]
  
  dist[start] = 0
  is_fixed[start] = true
  
  until queue.empty?
    queue.sort_by! { |i| dist[i] }
    
    tmp = queue.shift
    is_fixed[tmp] = true
    
    nodes[tmp].each do |from, to, cost, time|
      next if is_fixed[to]
      new_len = dist[from] + (value_as_dist == 0 ? cost : time)
      
      if new_len < dist[to]
        dist[to] = new_len
      end
    end
  end
  
  dist
end

while true
  n, m = gets.split.map(&:to_i)

  break if n + m == 0

  nodes = Array.new(m) { [] }
  memo = Array.new(m) { Array.new(2) }

  n.times do
    a, b, cost, time = gets.split.map(&:to_i)
    a -= 1
    b -= 1
    
    nodes[a] << [a, b, cost, time]
    nodes[b] << [b, a, cost, time]
  end
  
  gets.to_i.times do
    p_k, q_k, r_k = gets.split.map(&:to_i)
    p_k -= 1
    q_k -= 1

    memo[p_k][r_k] = dijekstra(p_k, nodes, r_k) if memo[p_k][r_k].nil?
    
    puts memo[p_k][r_k][q_k]
  end
end