def warshall_floyd(dist_matrix)
	dist = dist_matrix
	n = dist.size
	raise "dist_matrix is not square" if dist.any?{|row| row.size != n}

	next_dist = (1..n).map{ Array.new(n) }	
	(0..n-1).each{|k|
		dist_k = dist[k]
		(0..n-1).each{|i|
			dist_i = dist[i]
			next_dist_i = next_dist[i]
			(0..n-1).each{|j|
				x = dist_i[j]
				y = dist_i[k] + dist_k[j]
				next_dist_i[j] = (x < y ? x : y)
			}
		}
		dist = next_dist
	}
	dist
end

loop do
	n, m = gets.split.map &:to_i
	break if n == 0 
	c_mat = (1..m).map{[Float::INFINITY] * m}
	t_mat = (1..m).map{[Float::INFINITY] * m}
	(0..m-1).each do |i|
		c_mat[i][i] = t_mat[i][i] = 0
	end
	
	n.times do
		i, j, c, t = gets.split.map &:to_i	
		i -= 1
		j -= 1
		c_mat[i][j] = c_mat[j][i] = c
		t_mat[i][j] = t_mat[j][i] = t
	end
	
	c_mat = warshall_floyd(c_mat)
	t_mat = warshall_floyd(t_mat)
	
	q = gets.to_i
	q.times do
		i, j, k = gets.split.map &:to_i
		i -= 1
		j -= 1
		puts k == 0 ? c_mat[i][j] : t_mat[i][j]
	end
end