import Data.List
import qualified Data.ByteString.Char8 as B
import Control.Monad
import qualified Data.Array as A 

main :: IO ()
main = readLn >>= main'
    where
        main' n = replicateM n breads >>= main'' n . edit
        main'' n fs = replicateM n breads >>= print . solve n fs . edit2

edit :: [[Int]] -> [[Int]]
edit (x : xs) = zipWith (:) x $ edit xs
edit _ = replicate 10 []

edit2 :: [[Int]] -> [A.Array Int Int]
edit2 = fmap (A.listArray (0, 10))

solve :: Int -> [[Int]] -> [A.Array Int Int] -> Int
solve n fs ps = foldl' ff (-10000000000) . tail $ patterns 10
    where
        ff acc = max acc . foldl' ff3 0 . zip ps . foldl' ff2 (replicate n 0) . zip fs
        ff2 acc (xs, b)
            | b = zipWith (+) acc xs
            | otherwise = acc
        ff3 acc (p, i) = acc + p A.! i


patterns :: Int -> [[Bool]]
patterns n
    | n == 0 = [[]]
    | otherwise = (:) <$> [False, True] <*> patterns (n - 1)

     
breads :: IO [Int]
breads = unfoldr uff <$> B.getLine
    where
        uff b = check <$> B.readInt b
        check (a, b)
            | B.null b = (a, b)
            | otherwise = (a, B.tail b)