{-# LANGUAGE BangPatterns #-}

import qualified Data.ByteString.Char8 as C
import Data.Maybe
import qualified Data.Vector as V
import Data.Vector.Unboxed
import qualified Data.Vector.Unboxed.Mutable as MU
import Prelude hiding (drop, filter, splitAt, tail, unfoldr)

main = C.interact $ put . sol . get

get = unfoldr (C.readInt . C.dropWhile (<'0'))

put = C.unlines . fmap (C.pack . show) . V.toList

sol v = fmap (\q -> ds!(q!0)+ds!(q!1)) qs
  where
  n = v!0
  (v0,v1) = splitAt (3*(n-1)) $! tail v
  es = V.unfoldrN (n-1) (Just . splitAt 3) v0
  q = v1!0
  k = v1!1
  qs = V.unfoldrN q (Just . splitAt 2) $! drop 2 v1
  tr = V.foldl' (\t e -> V.accum V.snoc t [(e!0,(e!1,e!2)),(e!1,(e!0,e!2))]) (V.replicate (n+1) V.empty) es
  ds = create $ do
    ds <- MU.new (n+1)
    MU.unsafeWrite ds 0 0
    loop ds 0 (k,0)
    return ds
    where
    loop ds !p !(nd,d) = do
      MU.unsafeWrite ds nd d
      V.mapM_ (\(nd',d') -> loop ds nd (nd',d+d')) . V.filter ((/=p) . fst) $ tr V.! nd