import Data.List

untilFix f x = if f x == x then x else untilFix f (f x)

main = interact $ unlines . map (show . cdp) . unfoldr read' . lines
 where 
  read' (x:xs)
   | x == "0" = Nothing
   | otherwise = let (xs1,xs2) = splitAt (read x) xs in Just (map (map read . words) xs1, xs2)

cdp nss = (sum . concat) nss - (sum . concat . untilFix disappear) nss

disappear = reverse . transpose . map (filter (/= 0)) . transpose . reverse .
 map (concatMap (\g -> if length g >=3 then map (const 0) g else g) . group)