
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import Debug.Trace
import Control.Monad

type Point = Int
type Color = Int
type Dist  = Int
type Edge = (Color,Dist)
type Path = (Point,Edge)
type Tree = Map.Map Point [Path]

edgesFromPoint :: Point -> Tree -> [Path]
edgesFromPoint p tree = fromMaybe [] $ Map.lookup p tree

findPath :: Point -> Tree -> [Point] -> [Path] -> [Path]
findPath _ _ _ [] = []
findPath dest tree memo path =
  let (start,_) = last path in
  if start == dest then path else
  let ps = edgesFromPoint start tree in
  foo dest tree memo path ps

foo :: Point -> Tree -> [Point] -> [Path] -> [Path] -> [Path]
foo dest tree memo path [] = findPath dest tree memo (init path)
foo dest tree memo path (p:ps) =
  if fst p `elem` memo then foo dest tree memo path ps else
  findPath dest tree (fst p:memo) (path ++ [p])

createTree :: [[Int]] -> Map.Map Point [Path] -> Tree
createTree [] map = map
createTree (l:ls) map =
  let
    p = head l
    q = l!!1
    color = l!!2
    dist = l!!3
    pp = edgesFromPoint p map
    qq = edgesFromPoint q map
    edge = (color,dist)
    pathp = (q,edge)
    pathq = (p,edge)
    t = Map.insert p (pp++[pathp]) map
    m = Map.insert q (qq++[pathq]) t
  in
    createTree ls m

sumPath :: Color -> Dist -> [Path] -> Dist
sumPath color dist [] = 0
sumPath color dist ((_,(c,d)):ps) =
  let q = if c == color then dist else d in
  q + sumPath color dist ps

printList :: [Int] -> IO ()
printList ints = mapM_ putStrLn $ lines $ intercalate "\n" $ map show ints

main = do
  nums <- map read . words <$> getLine :: IO [Int]
  let n = head nums
  let j = last nums
  ns <- replicateM (n-1) getLine :: IO [String]
  js <- replicateM j getLine :: IO [String]
  let as = map (map read . words) ns :: [[Int]]
  let qs = map (map read . words) js :: [[Int]]
  let tree = createTree as Map.empty
  printList $ map (\l -> sumPath (l!!0) (l!!1) (findPath (l!!3) tree [l!!2] [((l!!2),(0,0))])) qs








