parse :: [String] -> [[[Int]]]
parse [] = []
parse (x:xs) = if n == 0 then [] else map (map read) (map words (take n xs)) : parse (drop n xs)
    where
        n = read x

addsumr :: [Int] -> [Int]
addsumr xs = xs ++ [sum xs]

addsumc :: [[Int]] -> [[Int]]
addsumc xs = xs ++ [sumc xs]
    where
        sumc :: [[Int]] -> [Int]
        sumc ys
            | any null ys = []
            | otherwise = sum (map head ys) : sumc (map tail ys)

show5 :: Show a => a -> String
show5 x = if n < 5 then replicate (5 - n) ' ' ++ s else s
    where
        n = length s
        s = show x

showMatrix :: Show a => [a] -> String
showMatrix = concat . map show5

solve :: [[Int]] -> [String]
solve = map showMatrix . addsumc . map addsumr

main :: IO ()
main = getContents
    >>= return . parse . lines
    >>= return . map solve
    >>= mapM_ (mapM_ putStrLn)