
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE BangPatterns #-}

module Main where

import Debug.Trace
import Control.Monad
--import Data.List
--import qualified Data.Set.Strict as Set
--import qualified Data.Map.Strict as Map
import qualified Data.IntMap.Strict as Map

main :: IO ()
main = do
  getLine
  as <- map read . words <$> getLine
  getLine
  qs <- map (map read . words) . lines <$> getContents 
  --a `traceShow`
  forM_ (solve as qs) $ \s -> do
    print s

solve :: [Int] -> [[Int]] -> [Int]
--solve as qs = ["aa", "bb", "cc"]
solve as qs = build tbl st qs
  where
    tbl = foldr (\a m -> Map.insertWith (+) a 1 m) Map.empty as
    st = sum as


--build :: Map.Map Int Int -> Int -> [[Int]] -> [Int]
build :: Map.IntMap Int -> Int -> [[Int]] -> [Int]
--build m ([b, c]:qs) =  m' `traceShow` (Map.foldrWithKey (\k a ks -> ks + k * a) 0 m') : build m' qs
build m !prev ([!b, !c]:qs) = cur : build m' cur qs
  where
    (cur ,m') = case Map.lookup b m of
      Just k -> (Map.foldrWithKey (\k a ks -> ks + k * a) 0 m', Map.insertWith (+) c k (Map.delete b m))
      Nothing -> (prev, m)
build m _ [] = []
