import Data.List(find,delete)
import Data.Maybe

slice :: Int -> [a] -> [[a]]
slice _ [] = []
slice n xs = let (y,ys) = splitAt n xs
             in  y : slice n ys

insert :: Int -> a -> [a] -> [a]
insert _ _ [] = []
insert n y xs = let (z,zs) = splitAt n xs
                in  z ++ y : insert n y zs

num xs y = val $ find (\x -> take 3 x == y) xs
    where val Nothing = "0"
          val (Just xs) = show $ last xs

f :: [[Int]] -> [[Int]]
f [] = []
f (x:xs) =  let x2 = find (\x2 -> take 3 x2 == take 3 x) xs
            in  if (x2 == Nothing) then
                    x : (f xs)
                else
                    let x2' = fromJust x2
                    in  f $ ((take 3 x) ++ [last x + last x2']) : (delete x2' xs)

main = do
    _ <- getLine
    cs <- getContents
    let xs = f (zipWith ($) (repeat (\c -> map read $ words c)) (lines cs))
    let ys = [[b,f,r] | b <- [1..4], f <- [1..3], r <- [1..10]]
    putStr $ unlines $ insert 3 (replicate 20 '#') $ slice 20 (" " ++ (unwords $ map (num xs) ys))